使用场景

更精细化的事务配置以及事务回归策略

关键代码

  1. @Override
  2. @Nullable
  3. public <T> T execute(TransactionCallback<T> action) throws TransactionException {
  4. Assert.state(this.transactionManager != null, "No PlatformTransactionManager set");
  5. if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
  6. return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action);
  7. }
  8. else {
  9. TransactionStatus status = this.transactionManager.getTransaction(this);
  10. T result;
  11. try {
  12. result = action.doInTransaction(status);
  13. }
  14. catch (RuntimeException | Error ex) {
  15. // Transactional code threw application exception -> rollback
  16. rollbackOnException(status, ex);
  17. throw ex;
  18. }
  19. catch (Throwable ex) {
  20. // Transactional code threw unexpected exception -> rollback
  21. rollbackOnException(status, ex);
  22. throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception");
  23. }
  24. this.transactionManager.commit(status);
  25. return result;
  26. }
  27. }

使用案例

事务设置

  1. public class UserService implements IUserService {
  2. private final TransactionTemplate transactionTemplate;
  3. public UserService(PlatformTransactionManager transactionManager) {
  4. this.transactionTemplate = new TransactionTemplate(transactionManager);
  5. // 配置事务隔离级别
  6. this.transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
  7. // 配置超时时间 (单位秒)
  8. this.transactionTemplate.setTimeout(30);
  9. }
  10. }

事务创建

  1. public class UserService implements Service {
  2. // 当前实例的所有方法 都可以使用
  3. private final TransactionTemplate transactionTemplate;
  4. // 通过构造方法注入
  5. public UserService(PlatformTransactionManager transactionManager) {
  6. this.transactionTemplate = new TransactionTemplate(transactionManager);
  7. }
  8. public Boolean save() {
  9. return transactionTemplate.execute(new TransactionCallback() {
  10. public Object doInTransaction(TransactionStatus status) {
  11. try {
  12. // 一些操作
  13. updateOperation1();
  14. updateOperation2();
  15. return Boolean.TRUE;
  16. } catch (SomeBusinessException ex) {
  17. // 可以配置那些异常需要回滚
  18. status.setRollbackOnly();
  19. return Boolean.FALSE;
  20. }
  21. }
  22. });
  23. }
  24. }

参考资料

事务相关【Spring官方文档】