I use EntityManager to save/update my entities in database and Hibernate as jpa provider. My transactions are handled by container.
The problem: I need to add an entity that might have been already stored in database, so an exception will be thrown. In this case I need to repeat insertion but with another value. But as long as an exception is thrown the session has gone bad and I need to create a new session and rollback the transaction. How can I do this when I’m using CMT? Or if there is another way to do this?
Thank you.
You could use the
TransactionAttribute(REQUIRES_NEW)for your persistence method. If the bean invoking your method will catch an exception, it might do some changes and invoke the method once again.This will rollback just the persistence-method transaction – not the invoking bean one.
However, remember that if your Use Case doesn’t require you to do
EntityManager#persistence(-), you might be interested inEntityManager#merge(-)operation. It will persist the entity if it doesn’t already exist or update it if it already exists (the existence is checked based on the PK).HTH.