Skip to main content

Developing with XCC

Enlisting MarkLogic Server in an XA Transaction

To use MarkLogic Server in an XA transaction, use the Session.getXAResource method to register your XCC session as a javax.transaction.xa.XAResource with the XA Transaction Manager.

The following code snippet shows how to enlist an XCC session in a global XA transaction. Once you enlist the Session, any work performed in the session is part of the global transaction. For complete code, see the sample code in com.marklogic.xcc.examples.XA.

javax.transaction.TransactionManager tm = ...;
Session session = ...;
try {
    // Begin a distributed transaction
    tm.begin();

   // Add the MarkLogic Session to the distributed transaction
    javax.transaction.xa.XAResource xaRes = session.getXAResource();
    tm.getTransaction().enlistResource(xaRes);

    // Perform MarkLogic Server updates under the global transaction
    session.submitRequest(session.newAdhodquery(
        "xdmp:document-insert('a', <a/>)"));

    // Update other databases here

    //Commit all updates together
    tm.commit();
} catch (Exception e) {
    e.printStackTrace();
    if (tm. getTransaction != null) tm.rollback();
} finally {
    session.close();
}

When MarkLogic Server acts as an XA transaction Resource Manager, requests submitted to the server are always part of a multi-statement update transaction, with the following important differences:

  • The Session.setAutoCommit and Session.setTransactionMode settings are ignored. The transaction is always a multi-statement update transaction, even if only a single request is submitted to MarkLogic Server during the global transaction.

  • The application should not call Session.commit or xdmp:commit(). The transaction is committed (or rolled back) as part of the global XA transaction. To commit the global transaction, use the Transaction Manager with which the MarkLogic Server XAResource is registered.

  • The application may call Session.rollback or xdmp:rollback(). Doing so eventually causes rollback of the global XA transaction. Rolling back via the Transaction Manager is usually preferable.

To learn more about multi-statement transactions, see Multi-statement Transactions.