【问题标题】:Hibernate: making transient objects persistent with SessionHibernate:使用 Session 使瞬态对象持久化
【发布时间】:2013-01-06 20:20:05
【问题描述】:

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

【问题讨论】:

    标签: hibernate persistence transient


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-06-14
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      相关资源
      最近更新 更多