Hibernate:使用Session使临时对象持久化

时间:2013-01-23 11:10:53

标签: hibernate persistence transient

我见过 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做同样的事情?

1 个答案:

答案 0 :(得分:0)

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

的回答