|
| 1 | +.. _java-fundamentals-transactions: |
| 2 | + |
| 3 | +============ |
| 4 | +Transactions |
| 5 | +============ |
| 6 | + |
| 7 | +.. contents:: On this page |
| 8 | + :local: |
| 9 | + :backlinks: none |
| 10 | + :depth: 2 |
| 11 | + :class: singlecol |
| 12 | + |
| 13 | +.. facet:: |
| 14 | + :name: genre |
| 15 | + :values: reference |
| 16 | + |
| 17 | +.. meta:: |
| 18 | + :keywords: ACID, write, consistency, code example |
| 19 | + |
| 20 | +Overview |
| 21 | +-------- |
| 22 | + |
| 23 | +In this guide, you can learn how to use the {+driver-short+} to perform |
| 24 | +**transactions**. :manual:`Transactions </core/transactions/>` allow |
| 25 | +you to run a series of operations that do not change any data until the |
| 26 | +transaction is committed. If any operation in the transaction returns an |
| 27 | +error, the driver cancels the transaction and discards all data changes |
| 28 | +before they ever become visible. |
| 29 | + |
| 30 | +In MongoDB, transactions run within logical **sessions**. A |
| 31 | +:manual:`session </reference/server-sessions/>` is a grouping of related |
| 32 | +read or write operations that you intend to run sequentially. Sessions |
| 33 | +enable :manual:`causal consistency |
| 34 | +</core/read-isolation-consistency-recency/#causal-consistency>` for a |
| 35 | +group of operations or allow you to execute operations in an |
| 36 | +:website:`ACID transaction </basics/acid-transactions>`. MongoDB |
| 37 | +guarantees that the data involved in your transaction operations remains |
| 38 | +consistent, even if the operations encounter unexpected errors. |
| 39 | + |
| 40 | +When using the {+driver-short+}, you can create a new session from a |
| 41 | +``MongoClient`` instance as a ``ClientSession`` type. We recommend that you reuse |
| 42 | +your client for multiple sessions and transactions instead of |
| 43 | +instantiating a new client each time. |
| 44 | + |
| 45 | +.. warning:: |
| 46 | + |
| 47 | + Use a ``ClientSession`` only with the ``MongoClient`` (or associated |
| 48 | + ``MongoDatabase`` or ``MongoCollection``) that created it. Using a |
| 49 | + ``ClientSession`` with a different ``MongoClient`` results in operation |
| 50 | + errors. |
| 51 | + |
| 52 | +.. important:: |
| 53 | + |
| 54 | + You must include the ``session`` as a parameter for any operations that you |
| 55 | + want to include in a transaction. |
| 56 | + |
| 57 | +Methods |
| 58 | +------- |
| 59 | + |
| 60 | +Create a ``ClientSession`` by using the ``startSession()`` method on your |
| 61 | +``MongoClient`` instance. You can then modify the session state by using the |
| 62 | +methods provided by the ``ClientSession``. The following table describes the |
| 63 | +methods you can use to manage your transaction: |
| 64 | + |
| 65 | +.. list-table:: |
| 66 | + :widths: 25 75 |
| 67 | + :header-rows: 1 |
| 68 | + |
| 69 | + * - Method |
| 70 | + - Description |
| 71 | + |
| 72 | + * - ``startTransaction()`` |
| 73 | + - | Starts a new transaction for this session with the |
| 74 | + default transaction options. Pass an instance of ``TransactionOptions`` |
| 75 | + as a parameter to start a transaction with given options. You |
| 76 | + cannot start a transaction if there's already an active transaction |
| 77 | + running in the session. |
| 78 | + | |
| 79 | + | **Parameter**: ``TransactionOptions transactionOptions`` |
| 80 | + |
| 81 | + * - ``abortTransaction()`` |
| 82 | + - | Ends the active transaction for this session. Returns an error |
| 83 | + if there is no active transaction for the |
| 84 | + session or the transaction was previously ended. |
| 85 | + |
| 86 | + * - ``commitTransaction()`` |
| 87 | + - | Commits the active transaction for this session. Returns an |
| 88 | + error if there is no active transaction for the session or if the |
| 89 | + transaction was ended. |
| 90 | + |
| 91 | + * - ``withTransaction()`` |
| 92 | + - | Starts a new transaction for this session and runs the given function. This |
| 93 | + method handles retries, committing, and aborting transactions. Pass an |
| 94 | + instance of ``TransactionBody`` as a parameter that defines the |
| 95 | + operations you want to execute within the transaction. |
| 96 | + | |
| 97 | + | **Parameter**: ``TransactionBody<T> transactionBody`` |
| 98 | + |
| 99 | +A ``ClientSession`` also has methods to retrieve session properties and modify mutable |
| 100 | +session properties. View the :ref:`API |
| 101 | +documentation <api-docs-transaction>` to learn more about these methods. |
| 102 | + |
| 103 | +Example |
| 104 | +------- |
| 105 | + |
| 106 | +The following example demonstrates how you can create a session, create a transaction, |
| 107 | +and commit a multi-document insert operation through the following steps: |
| 108 | + |
| 109 | +1. Create a session from the client by using the ``startSession()`` method. |
| 110 | +#. Set transaction options to configure transaction behavior. |
| 111 | +#. Use the ``withTransaction()`` method to start a transaction. |
| 112 | +#. Insert multiple documents. The ``withTransaction()`` method executes, commits, and aborts |
| 113 | + the transaction. If any operation results in errors, ``withTransaction()`` handles canceling |
| 114 | + the transaction. |
| 115 | + |
| 116 | +.. literalinclude:: /includes/fundamentals/code-snippets/Transaction.java |
| 117 | + :language: java |
| 118 | + :dedent: |
| 119 | + :start-after: start transaction |
| 120 | + :end-before: end transaction |
| 121 | + |
| 122 | +If you require more control over your transactions, you can use the ``startTransaction()`` |
| 123 | +method. You can use this method with the ``commitTransaction()`` and ``abortTransaction()`` |
| 124 | +methods described in the preceding section to manually manage the transaction lifecycle. |
| 125 | + |
| 126 | +Additional Information |
| 127 | +---------------------- |
| 128 | + |
| 129 | +To learn more about the concepts mentioned in this guide, see the following pages in |
| 130 | +the Server manual: |
| 131 | + |
| 132 | +- :manual:`Transactions </core/transactions/>` |
| 133 | +- :manual:`Server Sessions </reference/server-sessions>` |
| 134 | +- :manual:`Read Isolation, Consistency, and Recency </core/read-isolation-consistency-recency/#causal-consistency>` |
| 135 | + |
| 136 | +To learn more about ACID compliance, see the :website:`What are ACID |
| 137 | +Properties in Database Management Systems? </basics/acid-transactions>` |
| 138 | +article on the MongoDB website. |
| 139 | + |
| 140 | +.. _api-docs-transaction: |
| 141 | + |
| 142 | +API Documentation |
| 143 | +~~~~~~~~~~~~~~~~~ |
| 144 | + |
| 145 | +To learn more about any of the types or methods discussed in this |
| 146 | +guide, see the following API Documentation: |
| 147 | + |
| 148 | +- `ClientSession <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html>`_ |
| 149 | +- `startTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#startTransaction()>`_ |
| 150 | +- `commitTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#commitTransaction()>`_ |
| 151 | +- `abortTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#abortTransaction()>`_ |
| 152 | +- `withTransaction <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#withTransaction(com.mongodb.client.TransactionBody)>`_ |
| 153 | +- `TransactionOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/TransactionOptions.html>`_ |
| 154 | + |
0 commit comments