简体   繁体   English

spring @Transactional 不会回滚

[英]spring @Transactional is not rolling back

I have a similar piece of code inside a @Service :我在@Service有一段类似的代码:

@Autowired
private MyDAO myDAO;

@Transactional
@Override
public void m(...) {
    Integer i = null; // this is just to simulate a NPE
    myDAO.saveX(...);
    i.toString(); // throws NullPointerException
    myDAO.saveY(...);
}

This piece of code throws a NPE which is not catched by Spring and so my code is not rolled back.这段代码抛出了一个未被 Spring 捕获的 NPE,因此我的代码没有回滚。 Any idea why is this happening?知道为什么会这样吗?

I have the same configuration as in other places in my app and in those places it works as expected.我的配置与我的应用程序中其他地方的配置相同,在这些地方它按预期工作。

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

Possible reasons:可能的原因:

  1. Your bean is not managed by Spring, aka created with new instead of taken from the application context.您的 bean 不是由 Spring 管理的,也就是使用new创建而不是从应用程序上下文中获取。

  2. you're calling the m() method in another method of the same class/bean.您正在同一类/bean 的另一个方法中调用m()方法。 By default Spring uses proxies to manage declarative transactions and internal calls are not supported.默认情况下,Spring 使用代理来管理声明性事务,并且不支持内部调用。

  3. you're throwing checked exception and not using @Repository on the dao.您正在抛出已检查的异常,而不是在 dao 上使用@Repository Declarative transactions work only for runtime exceptions.声明性事务仅适用于运行时异常。 @Reposiotry "fixes" that by wrapping all exceptions in a DataAccessException . @Reposiotry 通过将所有异常包装在DataAccessException来“修复”。 (probably not the case since NPE is runtime) (可能不是这种情况,因为 NPE 是运行时)

尝试将rollbackFor参数添加到@Transactional注释中

@Transactional(rollbackFor=NullPointerException.class)

I found the solution here .我在这里找到了解决方案。 I have multiple contexts and some of them didn't have <tx:annotation-driven /> .我有多个上下文,其中一些没有<tx:annotation-driven />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM