Skip to main content

模版事务

模版事务会遵循下面这个通用逻辑:

try {
txManager.begin(propagation, isolation);

...

txManager.commit();
} catch (Throwable e) {
txManager.rollBack();
throw e;
}

使用模版事务代码如下:

TransactionTemplate template = ...
Object result = template.execute(new TransactionCallback<Object>() {
@Override
public Object doTransaction(TransactionStatus tranStatus) throws Throwable {
...
return null;
}
});
Java8 语法简化
Object result = template.execute(tranStatus -> {
return ...;
});
例:代码块在事务中执行,并忽略返回结果
template.execute((TransactionCallbackWithoutResult) tranStatus -> {
...
});

事务回滚

在模版事务中事务回滚有两种方式:

  • 方式1:抛出一个异常。
  • 方式2:通过 rollBackreadOnly 方法设置事务状态为回滚,该方式不会抛出异常。
回滚事务不抛出异常
Object result = template.execute(new TransactionCallback<Object>() {
public Object doTransaction(TransactionStatus tranStatus) {
tranStatus.setReadOnly();
// 或
tranStatus.setRollback();

return ...;
}
});

获取事务管理器

通过 DataSource 获取
DataSource dataSource = ...
TransactionManager txManager = TransactionHelper.txManager(dataSource);
通过 依赖注入 获取
public class TxExample {
// @Inject < Guice、Solon 和 Hasor
// @Resource or @Autowired < Spring
private TransactionManager txManager;
...
}
依赖注入方式使用请参考对应的文档