jakarta-eeejb-3.0jtajava-ee-5xa

Multiple XA data sources in a single JTA transaction


I have been programming with the Java EE platform for a while, but sometimes I am missing the bigger picture.

Using a EJBs and Container-Managed Transactions, how can I perform operations on multiple data sources in a single transaction?

My code looks like this:

aaa-ejb module

Contains a persistence.xml pointing to the first data source.

@Stateless
public class AaaDao {
    @PersistenceContext
    EntityManager em;

    // using defaults: @TransactionAttribute(REQUIRED)
    public void foo(...) {
        em.persist(...);
    }
}

bbb-ejb module

Contains another persistence.xml (a different persistence unit) pointing to the second data source.

@Stateless
public class BbbDao {
    @PersistenceContext
    EntityManager em;

    // using defaults: @TransactionAttribute(REQUIRED)
    public void bar(...) {
        em.persist(...);
    }
}

ccc-ejb module

Depends on the above two modules.

@Stateless
public class CccBean {
    @EJB AaaDao aaaDao;
    @EJB BbbDao bbbDao;

    // using defaults: @TransactionAttribute(REQUIRED)
    public void qux(...) {
        aaaDao.foo(...);
        bbbDao.bar(...);
    }
}

I mean: is it really that easy? I am always a little skeptical when things seems to work "magically", I always suspect there is a "catch".

Using Java EE 5, EJB 3.0, JPA 1.0 on Oracle WebLogic 10.3.


Solution

  • Yes, it is really that easy. CccBean.qux starts a new XA transaction, the callers to AaaDao/BbbDao reuse the same transaction (because of REQUIRED as you point out). The EntityManager use DataSource's and the DataSource will enlistResource an XAResource with the Transaction. When CccBean.qux exits, the transaction will be committed, and the transaction manager will drive 2-phase commit on both XAResource registered by the DataSource's.