spring的service不启动事务的配置。
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
原來是這樣設(shè)置的:
?? ? ? ?<tx:attributes>
?? ? ? ? ? ?<tx:method name="*" read-only="true"/>
?? ? ? ?</tx:attributes>
發(fā)現(xiàn)selectA調(diào)用selectB,如果selectB拋出Exception,selectA中捕獲Exception但是并不繼續(xù)向外拋出,最后會(huì)出現(xiàn)錯(cuò)誤。
?
Transaction rolled back because it has been marked as rollback-only
糾其原理其實(shí)很簡單,在selectB返回的時(shí)候,transaction被設(shè)置為rollback-only了,但是selectA正常消化掉,沒有繼續(xù)向外拋。
那么selectA結(jié)束的時(shí)候,transaction會(huì)執(zhí)commit操作,但是transaction已經(jīng)被設(shè)置為rollback-only了。
所以會(huì)出現(xiàn)這個(gè)錯(cuò)誤。
有的同學(xué)說了,那不是沒得搞了,service不能拋出異常,或者不能攔截異常了?
其實(shí)不然,其實(shí)錯(cuò)誤不在這里,而是select這種操作為什么要啟動(dòng)事務(wù)呢?
調(diào)整好問題,找解決方案,問題就出現(xiàn)在propagation="REQUIRED"這個(gè)屬性上。
標(biāo)準(zhǔn)文檔上這樣寫:
| 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. |
?
看來我們需要如下修改:
?? ? ? ?<tx:attributes>
?? ? ? ? ? ?<tx:method name="*" read-only="true" propagation="NOT_SUPPORTED"/>
?? ? ? ?</tx:attributes>
這樣select這樣的檢索操作根本就不啟動(dòng)事務(wù)了,而且在有事務(wù)的方法中也是可以正常調(diào)用select方法的。
現(xiàn)在就沒問題了。
但是現(xiàn)在出現(xiàn)了另外一個(gè)問題,就是,如果在一個(gè)事物內(nèi)對db進(jìn)行操作,然后在出事物之前對剛才db操作的數(shù)據(jù)進(jìn)行select是獲取不到修改結(jié)果的,為什么呢?因?yàn)閚ot——supported是會(huì)在執(zhí)行select之前掛起原有事物,不在原有事物內(nèi),當(dāng)然無法獲得修改后的數(shù)據(jù)。
怎么辦?改成supports:
?? ? ? ?<tx:attributes>
?? ? ? ? ? ?<tx:method name="*" read-only="true" propagation="SUPPORTS"/>
?? ? ? ?</tx:attributes>
這個(gè)狀態(tài)用一句話概括就是“有則加入事物,無也不創(chuàng)建事物”。
轉(zhuǎn)載于:https://my.oschina.net/jing31/blog/10414
總結(jié)
以上是生活随笔為你收集整理的spring的service不启动事务的配置。的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: currentTitle的用法
- 下一篇: css 水平垂直居中那些事