TransactionTemplate 编程式事务使用

1
2
3
4
5
6
7
8
9
10
public void dealUser(Map map2) throws Exception {
try {
transactionTemplate.execute(transactionStatus -> {
//数据库操作
return true;
});
} catch (Exception e) {
throw new Exception();
}
}

transactionTemplate.execute源码解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public <T> T execute(TransactionCallback<T> action) throws TransactionException {
Assert.state(this.transactionManager != null, "No PlatformTransactionManager set");
if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
return ((CallbackPreferringPlatformTransactionManager)this.transactionManager).execute(this, action);
} else {
TransactionStatus status = this.transactionManager.getTransaction(this);

Object result;
try {
result = action.doInTransaction(status);
} catch (Error | RuntimeException var5) {
this.rollbackOnException(status, var5);
throw var5;
} catch (Throwable var6) {
this.rollbackOnException(status, var6);
throw new UndeclaredThrowableException(var6, "TransactionCallback threw undeclared checked exception");
}

this.transactionManager.commit(status);
return result;
}
}

不难看出execute方法和声明式事务的处理方法也差不多,也是捕获异常的话,就回退并继续抛出异常,否则就尝试提交,这里之所以说尝试提交,就和transactionStatus.setRollbackOnly();有关系

transactionStatus.setRollbackOnly

为什么使用transactionStatus.setRollbackOnly();不抛出异常,也可以回退,我们看代码得知,唯一能回退的代码只可能在this.transactionManager.commit(status);里面了,我们看一下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public final void commit(TransactionStatus status) throws TransactionException {
if (status.isCompleted()) {
throw new IllegalTransactionStateException("Transaction is already completed - do not call commit or rollback more than once per transaction");
} else {
DefaultTransactionStatus defStatus = (DefaultTransactionStatus)status;
//就在这里,这里判断一下是否设置了仅回退,如果设置了,直接回退
if (defStatus.isLocalRollbackOnly()) {
if (defStatus.isDebug()) {
this.logger.debug("Transactional code has requested rollback");
}

this.processRollback(defStatus, false);
} else if (!this.shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
if (defStatus.isDebug()) {
this.logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
}

this.processRollback(defStatus, true);
} else {
this.processCommit(defStatus);
}
}
}

看代码很容易就看出来了,做了判断,判断一下是否设置了仅回退,如果设置了,直接回退


本站总访问量:次本站总访问数:人
本站由 Peng Tong 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。