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?
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.
来源:https://stackoverflow.com/questions/3726151/how-do-i-catch-exceptions-from-container-managed-transaction-commit