Docs Menu
Docs Home
/ / /
Kotlin Sync ドライバー
/

トランザクション

項目一覧

  • Overview
  • サンプル データ
  • メソッド
  • 詳細情報
  • API ドキュメント

このガイドでは、 Kotlin Syncドライバーを使用してトランザクションを実行する方法を学習できます。トランザクション を使用すると、トランザクションがコミットされるまでデータを変更しない一連の操作を実行できます。トランザクション内のいずれかの操作でエラーが返された場合、ドライバーはトランザクションをキャンセルし、変更が反映される前にすべてのデータ変更を破棄します。

MongoDB では、トランザクションは論理セッション内で実行されます。 セッションは 、順番に実行されるよう関連付けられた読み取り操作または書き込み操作のグループです。 セッションにより、一連の操作に対する因果整合性が有効になり、 ACID 準拠のトランザクション(不可分性、整合性、分離、耐久性の期待を満たすトランザクション)内で操作を実行できるようになります。 MongoDBは、トランザクション操作で予期せぬエラーが発生した場合でも、その操作に関わるデータの一貫性が保たれることを保証します。

Kotlin Syncドライバーを使用すると、 MongoClientインスタンスからClientSessionタイプの新しいセッションを作成できます。毎回新しいクライアントを作成するのではなく、 MongoClientを複数のセッションやトランザクションで再利用することを推奨します。

警告

ClientSession は、それを作成した MongoClient(または関連付けられたMongoDatabase または MongoCollection)でのみ使用します。ClientSession と、異なる MongoClient を使用すると、操作エラーが発生します。

このガイドの例では、 Atlas サンプル データセットsample_restaurants.restaurantsコレクションを使用します。 MongoDB Atlas クラスターを無料で作成して、サンプル データセットをロードする方法については、 「 Atlas を使い始める 」ガイドを参照してください。

このコレクション内のドキュメントは、次の Kotlin データ クラスによってモデル化されます。

data class Restaurant(val name: String, val cuisine: String)

MongoClientインスタンスでstartSession()メソッドを使用してClientSessionを作成します。 次に、 ClientSessionが提供するメソッドを使用して、セッション状態を変更できます。 次の表では、トランザクションを管理するために使用できる方法について説明します。

方式
説明
startTransaction()
Starts a new transaction, configured with the given options, on this session. Returns an error if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions
abortTransaction()
Ends the active transaction for this session. Returns an error if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

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. To learn more about this method, see the commitTransaction() page in the Server manual.
withTransaction()
Starts a transaction on this session and runs the given function within a transaction.

Parameters: transaction body function, TransactionOptions

次の例は、セッションを作成し、トランザクションを作成し、次の手順で 1 つのトランザクション内でコレクションにドキュメントを挿入する方法を示しています。

  1. startSession()メソッドを使用してクライアントからセッションを作成します。

  2. 複数のドキュメントをrestaurantsコレクションに挿入するには、 insertRestaurantsInTransaction()メソッドを定義します。

  3. トランザクションを開始するには、 withTransaction()メソッドを使用します。 withTransaction()メソッドは挿入操作を実行し、トランザクションをコミットします。いずれかの操作でエラーが発生した場合、 withTransaction()はトランザクションをキャンセルします。

  4. MongoClient.close()メソッドを使用してサーバーへの接続を閉じます。

// Creates a new MongoClient to manage your connection
val client = MongoClient.create("<connection string>")
// Gets the database and collection
val database = client.getDatabase("sample_restaurants")
val collection = database.getCollection<Restaurant>("restaurants")
// Inserts restaurants into the collection
fun insertRestaurantsInTransaction(session: ClientSession) {
// Inserts restaurants within the transaction
collection.insertOne(
session,
Restaurant("Kotlin Sync Pizza", "Pizza")
)
collection.insertOne(
session,
Restaurant("Kotlin Sync Burger", "Burger")
)
}
// Starts a client session
client.startSession().use { session ->
try {
// Sets transaction options
val txnOptions = TransactionOptions.builder()
.readConcern(ReadConcern.LOCAL)
.writeConcern(WriteConcern.MAJORITY)
.build()
// Uses the withTransaction method to start a transaction and run the given function
session.withTransaction({
insertRestaurantsInTransaction(session)
println("Transaction succeeded")
}, txnOptions)
} catch (e: Exception) {
println("Transaction failed: ${e.message}")
}
}
// Closes the MongoClient
client.close()

トランザクションをさらに制御する必要がある場合は、 startTransaction()メソッドを使用できます。 このメソッドを前のセクションで説明した メソッドとcommitTransaction() abortTransaction()メソッドと組み合わせて使用すると、トランザクションのライフサイクルを手動で管理できます。

このガイドで言及されている概念の詳細については、サーバー マニュアルの次のページを参照してください。

ACID compliance の詳細については、 「 データベース管理システムの ACID プロパティとは 」を参照してください。 MongoDB Webサイトの記事。

このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。

戻る

一括書き込み操作