spring @Transactional事务失效

 不开事务几种情形

① @Transactional写在了private方法上

org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource#computeTransactionAttribute

 

② 普通方法doTask3调用同一个类中有注解的方法doTask3Out, 并没有开启事务

 

 

参考:

https://www.cnblogs.com/milton/p/6046699.html

https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative-annotations

https://www.ibm.com/developerworks/cn/java/j-master-spring-transactional-use/index.html

同一个事务中会做 多个Dao操作,它们使用的jdbc connection是同一个,因为在同一个线程中,connection id可以保存在ThreadLocal中

 

③异步线程是否开始新事务,和非异步的主线程有关系吗

    @Transactional
public void doTask1() {
doTask2In();

//此处方法3上面的注解失效了!!!!
new Thread(()->{doTask3Out();}).start();
}
这个情况和情形2类似. 多线程编程时要注意, 没事别乱开线程

解决方法是使用AspectJ拦截事务, 不使用spring 默认的aop拦截事务



事务开始与连接获取的源码分析
org.springframework.jdbc.datasource.DataSourceTransactionManager#doBegin
org.springframework.transaction.annotation.Isolation中定义了几个事务的隔离级别:默认,读已提交 , 读未提交,序列化



多数据源配置: https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#tx-multiple-tx-mgrs-with-attransactional

 

 

Spring团队的建议是你在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。你当然可以在接口上使用 @Transactional 注解,但是这将只能当你设置了基于接口的代理时它才生效。因为注解是 不能继承 的,这就意味着如果你正在使用基于类的代理时,那么事务的设置将不能被基于类的代理所识别,而且对象也将不会被事务代理所包装(将被确认为严重的)。因 此,请接受Spring团队的建议并且在具体的类上使用 @Transactional 注解。

 

参考

Fescar分布式事务 https://my.oschina.net/keking/blog/3011509

 

 

 






 

posted @ 2018-08-30 19:34  funny_coding  阅读(2913)  评论(0编辑  收藏  举报
build beautiful things, share happiness