使用场景
更精细化的事务配置以及事务回归策略
关键代码
@Override
@Nullable
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);
T result;
try {
result = action.doInTransaction(status);
}
catch (RuntimeException | Error ex) {
// Transactional code threw application exception -> rollback
rollbackOnException(status, ex);
throw ex;
}
catch (Throwable ex) {
// Transactional code threw unexpected exception -> rollback
rollbackOnException(status, ex);
throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
}
this.transactionManager.commit(status);
return result;
}
}
使用案例
事务设置
public class UserService implements IUserService {
private final TransactionTemplate transactionTemplate;
public UserService(PlatformTransactionManager transactionManager) {
this.transactionTemplate = new TransactionTemplate(transactionManager);
// 配置事务隔离级别
this.transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
// 配置超时时间 (单位秒)
this.transactionTemplate.setTimeout(30);
}
}
事务创建
public class UserService implements Service {
// 当前实例的所有方法 都可以使用
private final TransactionTemplate transactionTemplate;
// 通过构造方法注入
public UserService(PlatformTransactionManager transactionManager) {
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
public Boolean save() {
return transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
try {
// 一些操作
updateOperation1();
updateOperation2();
return Boolean.TRUE;
} catch (SomeBusinessException ex) {
// 可以配置那些异常需要回滚
status.setRollbackOnly();
return Boolean.FALSE;
}
}
});
}
}
参考资料
事务相关【Spring官方文档】