Spring Data JPA 上的嵌套 @Transactional 注释行为

Nested @Transactional annotation behaviour on Spring Data JPA

我有一个实体User,一个Repository/DaoclassUserDao(使用Spring数据JPA ) 和服务 class UserService 方法 addUser 注释为 @Transactional:

@Service
public class UserService {

  @Autowired
  private UserDao userDao;

  @Transactional
  public void addUser() throws Exception {

    User user = new User();
    user.setUsername("aaa");

    // Save the user, but since this method have the @Transactional
    // annotation it should not be committed....
    userDao.save(user);

    // Forcing an error here I expected that the previous operation
    // were rolled back.. Instead the user is saved in the db.
    if ("".equals("")) {
      throw new Exception("something fails");
    }

    // Other operations (never executed in this example)
    user.setUsername("bbb");
    userDao.save(user);

    return;
  } // method addUser

} // class UserService

UserDao就是这样:

@Transactional
public interface UserDao extends CrudRepository<User, Long> { }

读取 Spring 数据 JPA documentation and other questions on the same argument (1, 2) 我的期望是,如果发生某些错误,标记为 @Transactional 的方法中的每个操作都将回滚..

我做错了什么? 如果发生错误,是否可以回滚上一个示例中的保存操作?

您需要向 Xml 配置文件中添加内容。您需要添加事务管理器。

 <tx:annotation-driven transaction-manager="txMgrDataSource" />

<!-- Creating TransactionManager Bean, since JDBC we are creating of type
    DataSourceTransactionManager -->
<bean id="txMgrDataSource"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="DataSource" />
</bean>

假设您的数据源是:

<bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="####" />
    <property name="url"
              value="jdbc:sqlConnection" />
    <property name="username" ref="user" />
    <property name="password" ref="pass" />

</bean>

您的理解是正确的,但自动回滚仅发生在运行时、未经检查的异常中。

因此,假设您的事务管理器配置正确,要在非运行时回滚,已检查的异常将 rollbackFor 属性添加到您的事务注释:

@Transactional(rollbackFor=Exception.class)
public void addUser() throws Exception {

}