java Spring Boot 事务性不回滚

6pp0gazn  于 2023-02-14  发布在  Java
关注(0)|答案(1)|浏览(228)

我正在尝试回滚带有@Transactional注解的更新。
但它对任何异常都不起作用。

public abstract class MyService<T1 extends MyDao<T2>, T2 extends MyMapper> {

  private final T1 myDao;

  public MyService( T1 myDao ) {
    this.myDao = myDao;
  }

  public updateSomething() {
    try {
      myDao.updateSomething();
    } catch (Exception e) {
      ...
    }
  }
}

@RequiredArgsConstructor
public abstract class MyDao<T extends MyMapper> {

  private final T myMapper;

  @Transactional( rollbackFor = Exception.class )
  public void updateSomething() throws Exception {
    myMapper.updateSomething();

    throw new Exception();
  }
}

当我在MyDao.updateSomething()中抛出异常时,回滚不起作用。
我尝试将@Transactional注解移动到MyService.updateSomething()并删除try-catch,结果相同。
我看到了事务回滚日志,但没有回滚。

[DEBUG ] o.s.j.d.DataSourceTransactionManager[processRollback:833] - Initiating transaction rollback
[DEBUG ] o.s.j.d.DataSourceTransactionManager[doRollback:345] - Rolling back JDBC transaction on Connection [HikariProxyConnection@1241981043 wrapping net.sf.log4jdbc.sql.jdbcapi.ConnectionSpy@1347fc2]
[DEBUG ] o.s.j.d.DataSourceTransactionManager[doCleanupAfterCompletion:389] - Releasing JDBC Connection [HikariProxyConnection@1241981043 wrapping net.sf.log4jdbc.sql.jdbcapi.ConnectionSpy@1347fc2] after transaction

为什么回滚不起作用?

c90pui9n

c90pui9n1#

默认情况下,Spring会回滚RuntimeException的事务,所以如果要回滚,应该使用普通的@Transactional并抛出RuntimeException
还要确保不要在myMapper.updateSomething()中启动另一个事务。

相关问题