我正在使用 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;
}
任何人都知道为什么第二次调用也会引发异常以及如何第二次修复它?