Search code examples
rollbackpojotransactionalpropagation

Java EE Transaction propagation with POJO calls in-between


Below is the source code of an EJB class 1:

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EJB1 {

  public void method1(Callback callback) {
    callback.createObject();
    Entity1 entity = new Entity1();
    try {
      entityManager.persist(entity1);
      entityManager.flush()
    } catch(Exception e) {
      //do something
    }
  }
}

The Callback-class is a POJO has no TransactionalContext and calls another method of EJB 2 (looked up via JNDI), having again TransactionAttribute.REQUIRED:

public class Callback {

  public void createObject() {
    getEJB2().createObject();
  }

  public EJB2 getEJB() {
    //lookup EJB2 via JNDI
  }
}

Source code of EJB2:

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EJB2 {

  public void createObject() {
     Entity2 entity = new Entity2();
     entityManager.persist(entity);
      entityManager.flush()
  }
}

In case of persisting entity1 in EJB1 fails (e.g. due to an UniqueConstraint in the database) the transaction of EJB1 is successfully marked as rollback. For instance when trying to delete the created object in the try-catch of EJB1 doesn't work (as transaction is already marked for rollback).

Although the object created and persisted in EJB2 still exists and is not rollbacked! Setting - for experimental usage - the EJB2 transactional context to MANDATORY the creation still works perfectly (indicating that EJB2 does NOT create a new transaction and instead participates via REQUIRED in existing transaction).

But why is the newly created object in EJB2 not rollbacked?


Solution

  • In the meantime we were able to fix this problem as we changed our Java EE application server from WebLogic 10.0 to GlassFish 3 as well as changed the used persistence provider from OpenJPA 1.0.0.1 to EclipseLink 2.5.1.

    One of these changes fixed the problem, probably the switch to EclipseLink. Now the transaction is marked for rollback (which wasn't the problem before and is exactly as expected) and in addition the new persisted instance of Entity2 is deleted due to the rollback.

    Sorry, that I didn't mentioned this information before which made it maybe impossible to find the cause.