Transaction rolled back because it has been marked as rollback-only

来源:互联网 发布:网络机柜 尺寸 编辑:程序博客网 时间:2024/05/21 11:58

原来是这样设置的:

 

 

Xml代码  收藏代码
  1. <tx:attributes>  
  2.   
  3.            <tx:method name="*" read-only="true"/>  
  4.   
  5.        </tx:attributes>  
 

 

发现selectA调用selectB,如果selectB抛出Exception,selectA中捕获Exception但是并不继续向外抛出,最后会出现错误。

 

Transaction rolled back because it has been marked as rollback-only

纠其原理其实很简单,在selectB返回的时候,transaction被设置为rollback-only了,但是selectA正常消化掉,没有继续向外抛。

那么selectA结束的时候,transaction会执commit操作,但是transaction已经被设置为rollback-only了。

所以会出现这个错误。

有的同学说了,那不是没得搞了,service不能抛出异常,或者不能拦截异常了?

其实不然,其实错误不在这里,而是select这种操作为什么要启动事务呢?

调整好问题,找解决方案,问题就出现在propagation="REQUIRED"这个属性上。

标准文档上这样写:

MANDATORY 
          Support a current transaction, throw an exception if none exists.NESTED 
          Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.NEVER 
          Execute non-transactionally, throw an exception if a transaction exists.NOT_SUPPORTED 
          Execute non-transactionally, suspend the current transaction if one exists.REQUIRED 
          Support a current transaction, create a new one if none exists.REQUIRES_NEW 
          Create a new transaction, suspend the current transaction if one exists.SUPPORTS 
          Support a current transaction, execute non-transactionally if none exists.

 

看来我们需要如下修改:

 

 

Xml代码  收藏代码
  1. <tx:attributes>  
  2.   
  3.            <tx:method name="*" read-only="true" propagation="NOT_SUPPORTED"/>  
  4.   
  5.        </tx:attributes>  
 

这样select这样的检索操作根本就不启动事务了,而且在有事务的方法中也是可以正常调用select方法的。

现在就没问题了。

但是现在出现了另外一个问题,就是,如果在一个事物内对db进行操作,然后在出事物之前对刚才db操作的数据进行select是获取不到修改结果的,为什么呢?因为not——supported是会在执行select之前挂起原有事物,不在原有事物内,当然无法获得修改后的数据。

怎么办?改成supports:

 

  

Xml代码  收藏代码
  1. <tx:attributes>  
  2.   
  3.        <tx:method name="*" read-only="true" propagation="SUPPORTS"/>  
  4.   
  5.    </tx:attributes>  
 

 

这个状态用一句话概括就是“有则加入事物,无也不创建事物”。


原创粉丝点击