近期做收益项目,大规模使用spring的定时任务,然一些错误如Null Session,Not Proxy.代码无法应用.
前段时间查了下,发现一些解决方案.主要是查询之后session已经关闭,最佳方案是修改session的作用域,让其作用在整个service方法上.有些文档是要修改sessionFactory,需要编写xml配置文件.
看了下,感觉不符合springboot的风格.后来看了个方案,添加transcational注解.
@Transcational
昨天和别人在群里讨论了spring的事务,发现他们用的spring有自带事务和回滚控制,然后讨论得知他们是在xml文件里进行配置的.springboot中的事务是如何配置的,我做了几个小例子.
阶段1
编写了个updateTest()方法,修改一条记录并保存,其中有一段代码为
throw new NullPointerException("测试用");
然事务没回滚. 接着又改方法名为update(),还是没效果.
阶段2
加Transcational注解, 该注解是spring里的注解,非javax里的那个.
现在测试,事务已回滚.
阶段3
将该方法名修改为updateTest();在测试中,该事务回滚,这与spring的测试机制有关.
在正常的执行中,updateTest()方法也进行回滚.
阶段4
将方法修改为testCal();在spring的测试中回滚了.可能与spring的测试机制有关,只要在测试中加了@Transactional注解,出现异常就会回滚.
用url请求,仍出现异常回滚.
p>By default checked exceptions do not result in the transactional interceptor marking the
* transaction for rollback and instances of RuntimeException and its subclasses do. This default
* behavior can be modified by specifying exceptions that result in the interceptor marking the
* transaction for rollback and/or exceptions that do not result in rollback.</p>
* <p>The rollbackOn element can be set to indicate exceptions that must cause the interceptor to mark
* the transaction for rollback.</p>
* <p>Conversely, the dontRollbackOn element can be set to indicate
* exceptions that must not cause the interceptor to mark the transaction for rollback.</p>
* <p>When a class is specified for either of these elements, the designated behavior applies to subclasses
* of that class as well. If both elements are specified, dontRollbackOn takes precedence.</p>
默认,transcational不会对RuntimeException及其子类进行回滚. 但是如果回滚了,就用dontRollbackOn 属性指定RuntimeException不会滚,这样它本身和它的异常都不会使事务回滚.dontRollbackOn的优先级更高.
总结
spring-data-jpa的service层中的方法如果不加事务注解是不会回滚的,该注解可以加在类和方法上.现在的版本加上之后就会回滚,读者使用时可自行测试.rollBackOn属性指定回滚的异常类,dontRollBackOn属性,指定不回滚的异常类.
仅限于spring-boot中使用.
来源:oschina
链接:https://my.oschina.net/u/1590027/blog/792771