Transaction Manager
Hint
This article is generated by AI translation.
At an abstract level, the transaction manager exposes a few key methods:
| Method | Purpose |
|---|---|
| begin() | Start a transaction |
| commit(), commit(TransactionStatus) | Commit a transaction |
| rollBack(), rollBack(TransactionStatus) | Roll back a transaction |
| hasTransaction() | Check if a transaction exists |
info
The same transaction manager can open multiple transactions in sequence. See Propagation and Isolation for how they interact.
How it works
Each call to begin creates a new transaction and pushes it onto a transaction stack.
Example: three transactions via TransactionManager
DataSource dataSource = ...
TransactionManager txManager = new LocalTransactionManager(dataSource);
TransactionStatus tranA = txManager.begin();
TransactionStatus tranB = txManager.begin();
TransactionStatus tranC = txManager.begin();
...
txManager.commit(tranC);
txManager.commit(tranB);
txManager.commit(tranA);
On the transaction stack they appear like this; it is a standard LIFO stack:
+--------+--------+--------+ <<<< 入栈
| Tran A | Tran B | Tran C |
+--------+--------+--------+ >>>> 出栈
Note
With the transaction stack, dbVisitor allows operating on any position. For example, after opening three transactions you can commit them in one call.
DataSource dataSource = ...
TransactionManager manager = new LocalTransactionManager(dataSource);
TransactionStatus tranA = manager.begin();
TransactionStatus tranB = manager.begin();
TransactionStatus tranC = manager.begin();
...
manager.commit(tranA);
If you commit out of order, dbVisitor will automatically perform the needed sequence under the hood, equivalent to:
manager.commit(tranC);
manager.commit(tranB);
manager.commit(tranA);
How to use
dbVisitor provides three ways to work with transactions:
- Programmatic: call
LocalTransactionManagermethods directly. - Template: use the
TransactionTemplateinterface. - Annotation-based: rely on the
@Transactionannotation.