1717 * 事务执行器
1818 */
1919public class TxExecutor {
20- // 事务定义(传播行为是REQUIRES_NEW,即每次都开启一个新事务)
21- private static final TransactionDefinition TX_DEFINITION = new DefaultTransactionDefinition (TransactionDefinition .PROPAGATION_REQUIRES_NEW );
22-
23- // 事务管理器
24- private PlatformTransactionManager transactionManager ;
2520 // 事务持有器
26- private ThreadLocal <TransactionStatus > txStatusHolder = new ThreadLocal <>();
21+ private final ThreadLocal <TransactionStatus > txStatusHolder = new ThreadLocal <>();
22+ // 事务管理器
23+ private final PlatformTransactionManager transactionManager ;
24+ // 事务定义
25+ private final TransactionDefinition txDefinition ;
2726
28- public TxExecutor (PlatformTransactionManager transactionManager ) {
27+ public TxExecutor (PlatformTransactionManager transactionManager , boolean newTx ) {
2928 this .transactionManager = transactionManager ;
29+ if (newTx ) {
30+ txDefinition = new DefaultTransactionDefinition (TransactionDefinition .PROPAGATION_REQUIRES_NEW );
31+ } else {
32+ txDefinition = new DefaultTransactionDefinition (TransactionDefinition .PROPAGATION_REQUIRED );
33+ }
3034 }
3135
3236 /**
@@ -35,10 +39,12 @@ public TxExecutor(PlatformTransactionManager transactionManager) {
3539 * @throws IllegalStateException 如果已存在事务
3640 */
3741 public void createTx () {
38- if (txStatusHolder .get () != null ) {
39- throw new IllegalStateException ("本线程事务已存在,不能同时创建多个事务" );
42+ TransactionStatus txStatus = txStatusHolder .get ();
43+ if (txStatus != null ) {
44+ throw new IllegalStateException ("事务已存在,不能同时创建多个事务" );
4045 }
41- txStatusHolder .set (transactionManager .getTransaction (TX_DEFINITION ));
46+ txStatus = transactionManager .getTransaction (txDefinition );
47+ txStatusHolder .set (txStatus );
4248 }
4349
4450 /**
@@ -47,11 +53,12 @@ public void createTx() {
4753 * @throws IllegalStateException 如果不存在事务
4854 */
4955 public void commitTx () {
50- if (txStatusHolder .get () == null ) {
56+ TransactionStatus txStatus = txStatusHolder .get ();
57+ if (txStatus == null ) {
5158 throw new IllegalStateException ("事务不存在,无法提交事务" );
5259 }
53- transactionManager .commit (txStatusHolder .get ());
5460 txStatusHolder .remove ();
61+ transactionManager .commit (txStatus );
5562 }
5663
5764 /**
@@ -60,11 +67,12 @@ public void commitTx() {
6067 * @throws IllegalStateException 如果不存在事务
6168 */
6269 public void rollbackTx () {
63- if (txStatusHolder .get () == null ) {
70+ TransactionStatus txStatus = txStatusHolder .get ();
71+ if (txStatus == null ) {
6472 throw new IllegalStateException ("事务不存在,无法回滚事务" );
6573 }
66- transactionManager .rollback (txStatusHolder .get ());
6774 txStatusHolder .remove ();
75+ transactionManager .rollback (txStatus );
6876 }
6977
7078 /**
0 commit comments