【问题标题】:How do I make JPA entity manager forget about previous exceptions?如何让 JPA 实体管理器忘记以前的异常?
【发布时间】:2012-11-12 22:49:21
【问题描述】:

我正在使用 Hibernate 4.1.0.Final 和 hibernate-jpa-2.0-api。我遇到了一个问题,一旦我保存一个包含错误的实体,重复保存其他实体会给我与第一个实体报告的错误相同的错误,即使后续实体没有错误也是如此。这是我的实体:

@GenericGenerator(name = "uuid-strategy", strategy = "uuid.hex")
@Entity
@Table(name = "cb_organization", uniqueConstraints = {@UniqueConstraint(columnNames={"organization_id"})})
public class Organization implements Serializable
{

    …
    @ManyToOne(optional = false) 
    @JoinColumn(name = "country_id", nullable = false, updatable = false)
    /* The country the Organization is in */
    private Country country;

如果我尝试保存国家为空的实体,然后保存国家不为空的第二个实体,则第二次保存会引发 ConstraintViolationException 抱怨国家字段为空。

Organization org1 = new Organization();
…
org.setCountry(null);
orgDao.save(org1);      // We expect exception to be thrown, which it is.

Organization org2 = new Organization();
…
orgDao.setCountry(country); // set a valid Country object
orgDao.save(org2);  

这是相关的 DAO 代码...

@Autowired
private EntityManager entityManager;

@Override
public Organization save(Organization organization)
{
    if(StringUtils.isEmpty(organization.getId()))
    {
        entityManager.persist(organization);
    }
    else 
    {
        organization = entityManager.merge(organization);
    }
    entityManager.flush();

    return organization;
}

任何人都知道为什么第二次调用也会引发异常以及如何在第二次修复它?

【问题讨论】:

    标签: hibernate exception jpa entitymanager many-to-one


    【解决方案1】:

    我遇到了完全相同的问题。在第一个异常发生后,每个后续 JPA 查询结果都会出现相同的异常。事件简单选择查询。

    问题是我没有在交易之间关闭我的实体管理器。

    我通过在我的catch (PersistenceException e) 块中调用entityManager.clear() 解决了这个问题。我不确定这是否是正确的方法。

    编辑:更好的是,将clear() 调用移至finally 块。否则可能会导致内存泄漏。

    在此期间您是否找到了其他解决方案?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 2014-09-06
      • 2014-07-16
      相关资源
      最近更新 更多