三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

MongoDB事务处理实战

MongoDB事务处理实战

MongoDB事务处理实战

引言

MongoDB 4.0+支持多文档事务,提供了ACID保证。

事务操作

1.1 事务使用

import com.mongodb.client.ClientSession; import com.mongodb.client.MongoClient; /** * 事务处理 */ public class TransactionHandling { /** * 使用事务 */ public void executeTransaction(MongoClient mongoClient, MongoDatabase database) { try (ClientSession session = mongoClient.startSession()) { session.startTransaction(); try { MongoCollection<Document> orders = database.getCollection("orders"); MongoCollection<Document> inventory = database.getCollection("inventory"); orders.insertOne(session, new Document("item", "product1")); inventory.updateOne(session, Filters.eq("product", "product1"), Updates.inc("quantity", -1) ); session.commitTransaction(); } catch (Exception e) { session.abortTransaction(); throw e; } } } }

总结

事务为MongoDB提供了ACID保证。

← 返回列表