I'm using Hibernate 4.1.0.Final and hibernate-jpa-2.0-api. I'm having a problem whereby once I save an entity that contains an error, repeated saves on other entities give me the same error as what was reported for the first entity, even when the subsequent entities are error-free. Here's my entity:
@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;
If I try and save an entity where the country is null, and then save a second entity where the country is not null, the second save throws a ConstraintViolationException complaining about the country field being null.
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);
Here's the relevant DAO code ...
@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;
}
Anyone know why the second call is throwing an exception as well and how I can fix it the second time around?