Docs Menu
Docs Home
/ / /
Java Sync
/

Transactions

On this page

  • Overview
  • Methods
  • Example
  • Additional Information
  • API Documentation

In this guide, you can learn how to use the Java Driver to perform transactions. Transactions allow you to run a series of operations that do not change any data until the transaction is committed. If any operation in the transaction returns an error, the driver cancels the transaction and discards all data changes before they ever become visible.

In MongoDB, transactions run within logical sessions. A session is a grouping of related read or write operations that you intend to run sequentially. Sessions enable causal consistency for a group of operations or allow you to execute operations in an ACID transaction. MongoDB guarantees that the data involved in your transaction operations remains consistent, even if the operations encounter unexpected errors.

When using the Java Driver, you can create a new session from a MongoClient instance as a ClientSession type. We recommend that you reuse your client for multiple sessions and transactions instead of instantiating a new client each time.

Warning

Use a ClientSession only with the MongoClient (or associated MongoDatabase or MongoCollection) that created it. Using a ClientSession with a different MongoClient results in operation errors.

Important

You must include the session as a parameter for any operations that you want to include in a transaction.

Create a ClientSession by using the startSession() method on your MongoClient instance. You can then modify the session state by using the methods provided by the ClientSession. The following table describes the methods you can use to manage your transaction:

Method
Description
startTransaction()
Starts a new transaction for this session with the default transaction options. Pass an instance of TransactionOptions as a parameter to start a transaction with given options. You cannot start a transaction if there's already an active transaction running in the session.

Parameter: TransactionOptions transactionOptions
abortTransaction()
Ends the active transaction for this session. Returns an error if there is no active transaction for the session or the transaction was previously ended.
commitTransaction()
Commits the active transaction for this session. Returns an error if there is no active transaction for the session or if the transaction was ended.
withTransaction()
Starts a new transaction for this session and runs the given function. This method handles retries, committing, and aborting transactions. Pass an instance of TransactionBody as a parameter that defines the operations you want to execute within the transaction.

Parameter: TransactionBody<T> transactionBody

A ClientSession also has methods to retrieve session properties and modify mutable session properties. View the API documentation to learn more about these methods.

The following example demonstrates how you can create a session, create a transaction, and commit a multi-document insert operation through the following steps:

  1. Create a session from the client by using the startSession() method.

  2. Set transaction options to configure transaction behavior.

  3. Use the withTransaction() method to start a transaction.

  4. Insert multiple documents. The withTransaction() method executes, commits, and aborts the transaction. If any operation results in errors, withTransaction() handles canceling the transaction.

String connectionString = "<connection string>"; // Replace with your connection string
try (MongoClient mongoClient = MongoClients.create(connectionString)) {
MongoDatabase database = mongoClient.getDatabase("transaction_db");
MongoCollection<Document> collection = database.getCollection("books");
// Sets transaction options
TransactionOptions txnOptions = TransactionOptions.builder()
.writeConcern(WriteConcern.MAJORITY)
.build();
try (ClientSession session = mongoClient.startSession()) {
// Uses withTransaction and lambda for transaction operations
session.withTransaction(() -> {
collection.insertMany(session, Arrays.asList(
new Document("title", "The Bluest Eye").append("author", "Toni Morrison"),
new Document("title", "Sula").append("author", "Toni Morrison"),
new Document("title", "Song of Solomon").append("author", "Toni Morrison")
));
return null; // Return value as expected by the lambda
}, txnOptions);
}
} catch (Exception e) {
e.printStackTrace();
}

If you require more control over your transactions, you can use the startTransaction() method. You can use this method with the commitTransaction() and abortTransaction() methods described in the preceding section to manually manage the transaction lifecycle.

To learn more about the concepts mentioned in this guide, see the following pages in the Server manual:

To learn more about ACID compliance, see the What are ACID Properties in Database Management Systems? article on the MongoDB website.

To learn more about any of the types or methods discussed in this guide, see the following API Documentation:

Back

Indexes