5

springboot(19)编程式事务

 2 years ago
source link: https://wakzz.cn/2018/06/02/springboot/(19)%E7%BC%96%E7%A8%8B%E5%BC%8F%E4%BA%8B%E5%8A%A1/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

springboot(19)编程式事务

祈雨的博客
2018-06-02
@Autowired
private TransactionTemplate transactionTemplate;

Boolean isSuccess = transactionTemplate.execute(new TransactionCallback<Boolean>() {
public Boolean doInTransaction(TransactionStatus status) {
Boolean result = true;
try {
// TODO
} catch (Exception e) {
status.setRollbackOnly();
result = false;
// TODO
}
return result;
}
});

org.springframework.transaction.support.TransactionTemplate.execute() 方法有一个 TransactionCallback 类型的参数,该接口中定义了一个 doInTransaction() 方法,通常我们以匿名内部类的方式实现 TransactionCallback 接口,并在其 doInTransaction() 方法中书写业务逻辑代码。这里可以使用默认的事务提交和回滚规则,这样在业务代码中就不需要显式调用任何事务管理的 API。doInTransaction() 方法有一个TransactionStatus 类型的参数,我们可以在方法的任何位置调用该参数的setRollbackOnly() 方法将事务标识为回滚的,以执行事务回滚。

根据默认规则,如果在执行回调方法的过程中抛出了未检查异常,或者显式调用了TransacationStatus.setRollbackOnly() 方法,则回滚事务;如果事务执行完成或者抛出了checked类型的异常,则提交事务。

TransactionCallback接口有一个子接口 TransactionCallbackWithoutResult,该接口中定义了一个 doInTransactionWithoutResult() 方法,TransactionCallbackWithoutResult 接口主要用于事务过程中不需要返回值的情况。当然,对于不需要返回值的情况,我们仍然可以使用 TransactionCallback 接口,并在方法中返回任意值即可。

TransactionTemplate不可以在@Transactional注解的作用范围内使用,否则会导致异常:Transaction rolled back because it has been marked as rollback-only。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK