views:

35

answers:

1

Hi!

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?

+1  A: 

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.

bkail
Thank you for answering. I solved it by doing `EntityManager.flush()` in an `@AroundInvoke` interceptor.
Christoffer Hammarström
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