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

时间:2015-02-16 09:47:58

标签: java spring jpa spring-data spring-data-jpa

我有一个实体User,一个Repository / Dao类UserDao(使用 Spring Data JPA )和一个Service类UserService,其方法为{{ 1}}注释为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

阅读Spring Data JPA documentation以及关于同一论点(12)的其他问题,我的期望是标有@Transactional public interface UserDao extends CrudRepository<User, Long> { } 的方法中的每个操作都将如果发生某些错误,请回滚..

我做错了什么? 如果发生错误,是否有办法在前一个示例中回滚保存操作?

2 个答案:

答案 0 :(得分:3)

您的理解是正确的,但是仅对运行时未经检查的异常进行自动回滚。

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

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

}

答案 1 :(得分:0)

您需要向Xml配置文件添加内容..您需要添加trnasaction manager。

 <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>