MongoDB 从 4.0 版开始支持多文档 ACID 事务,Spring Data 则从 Lovelace 版开始支持原生 MongoDB 事务。
Maven 配置:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-reactivestreams</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.2.0.RELEASE</version>
<scope>test</scope>
</dependency>
使用 ReactiveMongoOperations.inTransaction()
:
@Autowired
private ReactiveMongoOperations reactiveOps;
@Test
public void test() {
User user1 = new User("Jane", 23);
User user2 = new User("John", 34);
reactiveOps.inTransaction()
.execute(action -> action.insert(user1)
.then(action.insert(user2)));
}
From Spring Data MongoDB Transactions.
Last modified: November 23, 2018
网友评论