Search code examples
jpaejbjava-ee-7stateless-session

How Stateless EJB rollback JPA transactions


Having for eg:

@Stateless

public class EntityRepositry{

    @Inject
    EntityManager em;

    public void create(Entity e){
       // op1 success
       // op2 failed
    }
}

As Stateless EJB are by default transactional, I would understand how the transaction if a system exception (like OptimisticLockedException) is thrown, will be rollbacked? How em.getTransaction().rollback will be called implicitly?

Thanks in advance.


Solution

  • EntityManager are injected with @PeristenceContext annotation (or may you have a CDI producer?)

    If the persistence unit is declared to use JTA transactions

    <persistence-unit name="myname" transaction-type="JTA">
    

    then the EJB transaction is bound to the JPA transaction and viceversa.

    JPA Exceptions rollback the whole transation but remember that any RuntimeException will rollback a transaction, checked exception doesn't.

    So if you use JTA transaction management you don't have to rollback manually transactions, just throw or catch the right exception (catching RuntimeException don't prevent the transaction to be rolled back but allow you to manage it).