0
votes

In our web application, we have a facade EJB which in turn calls multiple EJBs to perform a business function. The flow is like :

SLSB facade -> invokes ejb1, ejb2, ejb 3 etc -> invoke JPA layer

In each of the ejbs in the business layer, i inject entity manager using @PersistenceContext.

A simplified version of the code is as below:

@Stateless
public class facade{

  @EJB  
  private EJB1 ejb1;

  @EJB 
  private EJB2 ejb2; 
  @EJB ejb3;
  private EJB3 ejb3;

   public void performAction(..) {

    // invoke method on ejb1

    // invoke method on ejb2

    // invoke method on ejb3

    }


}

@Stateless
public class EJB1 implements IEjb1 {
    @PersistenceContext(unitName = "pu")
    private EntityManager entityManager;

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public xxxEntity insert(xxxEntity entity) throws AppException {
    // code for persisting the entity
    }               

}


@Stateless
public class EJB2 implements IEjb2 {
    @PersistenceContext(unitName = "pu")
    private EntityManager entityManager;

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public yyyEntity insert(yyyEntity entity) throws AppException {
    // code for persisting the entity
    }               

}

The application is deployed on Glassfish and uses JTA transaction. Since this is container managed PC, will the same persistence context be propagated to all EJBs? Will they run in the same transaction (reusing the transaction started in EJB1)? Is there a way to verify if the same transaction is used by all EJBs (same transaction id?)

1

1 Answers

0
votes

By default all ejbs (1,2,3) will participate in the one, same transaction that is started by facade ejb. You would need to define different transaction attribute for them to use different transactions (e.g. REQIRES_NEW to create new transaction).

If you really need transaction id, you could try to inject TransactionSynchronizationRegistry into your bean like this

@Resource
TransactionSynchronizationRegistry registry; 

// and then get key
...
registry.getTransactionKey() 

See TransactionSynchronizationRegistry and Container-Managed Transactions