@Transactional註解不回滾緣由詳解

最近試了試spring的回滾功能,根據網上的教程配置怎麼都很差使,遂尋找答案,html

網上的答案都是這麼講的:mysql

1. 檢查你方法是否是public的。spring

2. 你的異常類型是否是unchecked異常。
若是我想check異常也想回滾怎麼辦,註解上面寫明異常類型便可。sql

@Transactional(rollbackFor=Exception.class)

相似的還有norollbackFor,自定義不回滾的異常。數據庫

3. 數據庫引擎要支持事務,若是是mysql,注意表要使用支持事務的引擎,好比innodb,若是是myisam,事務是不起做用的。express

4. 是否開啓了對註解的解析mvc

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

5. spring是否掃描到你這個包,以下是掃描到org.test下面的包app

<context:component-scan base-package="org.test" ></context:component-scan>

我都檢查了,但就是不回滾,再找,終於發現了問題在哪兒..net

通常咱們在Spring的配置文件application.xml中對Service層代碼配置事務管理,能夠對Service的方法進行AOP加強或事務處理如事務回滾,可是遇到一個問題,在Controller類中調用Service層方法,配置的事務管理會失效,查詢相關資料發現緣由。其實Spring和SpringMVC倆個容器爲父子關係,Spring爲父容器,而SpringMVC爲子容器。也就是說application.xml中應該負責掃描除@Controller的註解如@Service,而SpringMVC的配置文件應該只負責掃描@Controller,不然會產生重複掃描致使Spring容器中配置的事務失效。code

最主要的是springmvc的配置文件,不能配置重複掃描Service,

能夠這樣配置

<context:component-scan base-package="com.zj.module.batis.controller"/>,

也能夠

<context:component-scan base-package="com.zj.module.batis">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>

直接過濾掉Service.

 

兩位博主的連接:

1.https://www.cnblogs.com/wuxiaofeng/p/6819209.html

2.https://blog.csdn.net/qq_32588349/article/details/52097943

相關文章
相關標籤/搜索