Skip to main content

Developing with XCC

Example: Using Multi-statement Transactions in Java

The following example demonstrates using multi-statement transactions in Java. The first multi-statement transaction in the session inserts two documents into the database, calling Session.commit to complete the transaction and commit the updates. The second transaction demonstrates the use of Session.rollback. The third transaction demonstrates implicitly rolling back updates by closing the session.

import java.net.URI;
import com.marklogic.xcc.ContentSource;
import com.marklogic.xcc.ContentSourceFactory;
import com.marklogic.xcc.Session;
public class SimpleMST {
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("usage: xcc://user:password@host:port/contentbase");
      return;
    }
    // Obtain a ContentSource object for the server at the URI.
    URI uri = new URI(args[0]);
    ContentSource contentSource =
        ContentSourceFactory.newContentSource(uri);
    // Create a Session and set the transaction mode to trigger
    // multi-statement transaction use.
    Session updateSession = contentSource.newSession();
    updateSession.setAutoCommit(false);
    updateSession.setUpdate(Session.Update.TRUE);
    // The request starts a new, multi-statement transaction. 
    updateSession.submitRequest(updateSession.newAdhocQuery(
    "xdmp:document-insert('/docs/mst1.xml', <data/>)"));
    // This request executes in the same transaction as the previous
    // request and sees the results of the previous update.
    updateSession.submitRequest(updateSession.newAdhocQuery(
    "xdmp:document-insert('/docs/mst2.xml', fn:doc('/docs/mst1.xml'));"));
    // After commit, updates are visible to other transactions.
    // Commit ends the transaction after current stmt completes.
    updateSession.commit();                    // txn ends, updates kept
    // Rollback discards changes and ends the transaction. 
    updateSession.submitRequest(updateSession.newAdhocQuery(
    "xdmp:document-delete('/docs/mst1.xml')"));
    updateSession.rollback();                // txn ends, updates lost
    // Closing session without calling commit causes a rollback.
    updateSession.submitRequest(updateSession.newAdhocQuery(
    "xdmp:document-delete('/docs/mst1.xml')"));
    updateSession.close();                    // txn ends, updates lost
  }
}