Ronald
Ronald

Reputation: 301

HIbernate persist object only with id

I have the folowing entity:

@Entity
@Table(name = "comprobante_pago")
public class ComprobantePago implements Serializable {

private Integer id;
private String serie;
private SocioNegocio emisor;
private Usuario usuario;


@Id
@Column(name = "id")
@SequenceGenerator(name = "seq", sequenceName = "comprobante_pago_id_seq",allocationSize=1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
public Integer getId() {
    return id;
}

@Column(name = "serie")
public String getSerie() {
    return serie;
}

public void setSerie(String serie) {
    this.serie = serie;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_emisor")
public SocioNegocio getEmisor() {
    return emisor;
}

public void setEmisor(SocioNegocio emisor) {
    this.emisor = emisor;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_usuario")
public Usuario getUsuario() {
    return usuario;
}

public void setUsuario(Usuario usuario) {
    this.usuario = usuario;
}
}

I want to persist a ComprobantePago object of the following way :

ComprobantePago cp = new ComprobantePago();
cp.setSerie("0001");
SocioNegocio emisor = new SocioNegocio();
emisor.setId(2);
Usuario usuario = new Usuario();
usuario.seId(10);
cp.setEmisor(emisor);
cp.setUsuario(usuario);
//persist the object
comprobantePagoDAO.crearComprobantePago(cp);

Where the ids of usuario(10) and emisor(2) are persisted in the respective entities, I make it in this way because I have only the ids of the entities.

In another class I have the method to persist the entity

public class ComprobantePagoDAOImpl implements ComprobantePagoDAO {

private SessionFactory sessionFactory;

@Override
public void crearComprobantePago(ComprobantePago comprobante) {
    sessionFactory.getCurrentSession().save(comprobante);
}
....
}

thank for all.

Upvotes: 1

Views: 1598

Answers (1)

JB Nizet
JB Nizet

Reputation: 692191

Don't create new, detached entities with only an ID, when what you actually want to do is link your new entity with persistent, managed entities that exist in the database.

Use EntityManager.getReference() instead, to get a persistent, managed entity from its ID. Or its equivalent in the Hibernate API: Session.load().

Upvotes: 2

Related Questions