1

我在http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html见过

使用 Hibernate Session 使对象持久化

但我不知道这是否意味着字面上使用 Session。说明:保存实例时出现以下错误:

org.springframework.dao.InvalidDataAccessApiUsageException: object references an unsaved transient instance - save the transient instance before flushing: xxxxxxx.entities.Sujeto.progTtipoSujeto -> xxxx.entities.TipoSujeto; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: xxxxx.entities.Sujeto.progTtipoSujeto -> xxxxx.entities.TipoSujeto
    at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:651)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:92)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:460)

我知道原因是 Sujeto.progTtipoSujeto 是 TipoSujeto 类型,它只是在保存 Sujeto 实例之前被实例化。此外,字段 progTtipoSujeto 与标识符字段联合:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "IDN_TIPO_SUJETO", insertable = false, updatable = false)
private TipoSujeto progTtipoSujeto;
@Column(name = "IDN_TIPO_SUJETO")
private Integer idnTipoSujeto;

我得到的解决方案(它有效)是在保存之前从数据库中获取它:

parserSujetoToEntity.parserSujetoToEntity(sujetoDTO, sujetoEntity);
TipoSujeto tipoSujetoEntity = (TipoSujeto) this.findByPrimaryKey(TipoSujeto.class, sujetoDTO.getTipo());
sujetoEntity.setProgTtipoSujeto(tipoSujetoEntity);
this.save(sujetoEntity);

有没有办法使用 Session 做同样的事情?

4

1 回答 1

0

由于您尝试使用相同的会话对象,因此可以使用会话的merge()方法。你可以参考这个答案

于 2013-01-23T13:25:30.747 回答