Docs 菜单
Docs 主页
/ / /
java sync
/

事务

在此页面上

  • 概述
  • 方法
  • 例子
  • 更多信息
  • API 文档

在本指南中,您可以了解如何使用 Java 驱动程序来执行事务事务允许您运行一系列操作,这些操作在提交事务之前不会更改任何数据。如果事务中的任何操作返回错误,驱动程序就会取消事务,并在所有数据更改变得可见之前将其丢弃。

在 MongoDB 中,事务在逻辑会话中运行。会话是一组要按顺序运行的相关读取或写入操作。会话可以实现一组操作的因果一致性,或支持在 ACID 事务中执行操作。MongoDB 保证事务操作中涉及的数据保持一致,即使操作遇到意外错误。

使用 Java 驱动程序时,您可以从 MongoClient实例创建一个新会话,并将其类型定义为ClientSession 。我们建议您将客户端重复用于多个会话和事务,而不是每次都实例化一个新客户端。

警告

仅应将 ClientSession 与创建它的 MongoClient(或关联的 MongoDatabaseMongoCollection)一起使用。将 ClientSession 与其他 MongoClient 一起使用会导致操作错误。

重要

对于要包含在事务中的任何操作,必须包含session作为参数。

MongoClient实例上使用startSession()方法创建ClientSession 。然后,您可以使用ClientSession提供的方法修改会话状态。下表描述了可用于管理事务的方法:

方法
说明
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

ClientSession还提供检索会话属性和修改可变会话属性的方法。查看API 文档以了解有关这些方法的更多信息。

以下示例演示了如何通过以下步骤创建会话、创建事务以及提交多文档插入操作:

  1. 使用 startSession() 方法从客户端创建会话。

  2. 设置事务选项以配置事务行为。

  3. 使用 withTransaction() 方法启动事务。

  4. 插入多个文档。 withTransaction()方法执行、提交和中止事务。如果任何操作导致错误, withTransaction()将处理取消事务。

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();
}

如果需要更好地控制事务,可以使用startTransaction()方法。您可以将此方法与上一节中描述的commitTransaction()abortTransaction()方法结合使用,以手动管理事务生命周期。

要了解有关本指南中提到的概念的更多信息,请参阅服务器手册中的以下页面:

要了解有关 ACID 合规性的更多信息,请参阅什么是数据库管理系统中的 ACID 属性? MongoDB 网站上的文章。

要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档:

后退

索引