Take the 2-minute tour ×

I have a @Stateless EJB with a @WebService interface, using container managed transactions, meaning transactions are automatically committed by the container after a method has been called if it doesn't throw a system exception.

If i try to EntityManager.persist(...) two objects with the same value for a column with a unique constraint on it, the container will throw a PersistenceException to the client on commit outside my code. How do i catch this exception so i can rethrow my own application exception?

Do i have to commit the transaction manually in my methods to catch exceptions on commit? (And is EntityManager.flush() the correct way to do that?) If so, what's the point of having container managed transactions?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

It is unfortunately not possible to catch exceptions from container-managed transaction failure. As you stated, your best option is to use bean-managed transactions. Alternatively, you could wrap your EM EJB with a proxy bean that implements the same interface. Container-managed transactions are appropriate when your code does not need to respond to specific commit failures.

share|improve this answer
Thank you for answering. I solved it by doing EntityManager.flush() in an @AroundInvoke interceptor. –  Christoffer Hammarström Oct 27 '10 at 9:23
That might work sometimes, but be careful with isolation levels. Unless you serialize everything, it's still possible to get failures when the tx commits. –  bkail Oct 28 '10 at 20:39

Your Answer


