Dave
Dave

Reputation: 19130

How do I make JPA entity manager forget about previous exceptions?

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?

Upvotes: 0

Views: 529

Answers (1)

alan.sambol
alan.sambol

Reputation: 265

I had exactly the same problem. After the first exception occurs every subsequent JPA query results with the same exception. Event simple select queries.

The problem is I don't close my entity manager between transactions.

I solved it by calling entityManager.clear() in my catch (PersistenceException e) block. I'm not sure if that's the right approach.

EDIT: Even better, move the clear() call to the finally block. Otherwise it may cause memory leaks.

Have you found another solution in the meantime?

Upvotes: 1

Related Questions