简体   繁体   English

仅带有 id 的 HIbernate 持久对象

[英]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 对象:

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.在 usuario(10) 和 emisor(2) 的 id 保留在各自的实体中的情况下,我这样做是因为我只有实体的 id。

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.谢谢大家。

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.不要创建只有一个 ID 的新的、分离的实体,当您真正想要做的是将您的新实体与数据库中存在的持久的、受管的实体相关联时。

Use EntityManager.getReference() instead, to get a persistent, managed entity from its ID.改用EntityManager.getReference()从其 ID 获取持久的托管实体。 Or its equivalent in the Hibernate API: Session.load() .或者它在 Hibernate API 中的等价物: Session.load()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM