1. 程式人生 > >@Transactional事務不回滾問題

@Transactional事務不回滾問題

 一、

<!-- Start SpringMVC配置 -->  
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext*.xml</param-value>
	</context-param>
	<servlet>  
	    <servlet-name>springmvc</servlet-name>  
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
	    <init-param>  
	        <param-name>contextConfigLocation</param-name>  
			<param-value>classpath:spring-mvc.xml</param-value>
	    </init-param>
	    <load-on-startup>1</load-on-startup>  
	</servlet>  
	<servlet-mapping>  
	    <servlet-name>springmvc</servlet-name>  
	    <url-pattern>*.mvc</url-pattern>  
	</servlet-mapping>  
	<!-- End SpringMVC配置 -->  

如上圖Spring事務配置檔案還有上下文都是通過org.springframework.web.context.ContextLoaderListener載入的,而spring MVC的Controller是通過org.springframework.web.servlet.DispatcherServlet載入的 。所以包掃描配置需要分開放

<!-- applicationContext.xml:這是能過ContextLoaderListener載入的,載入時需要排除掉Controller避免二次載入,當然我這裡直接指定到了service 不排除也不會受影響,因為二次載入也會影響到事務不生效。 -->
<context:component-scan base-package="cn.test.web.*.service.*">
	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

 

<!--  掃描控制器放在Spring-mvc.xml配置檔案中,同上也只掃描Controller,避免同時掃描到service導致事務不生效 -->
<context:component-scan base-package="cn.transfar.web.*.controller">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>

 二、

檢查是否增加了註解驅動的事務管理,並增加AOP自動代理功能,這裡可能會需要相入cglib.2.1_3.jar包,否則會報錯

<!--支援註解驅動的事務管理,指定事務管理器 -->
<tx:annotation-driven transaction-manager="transactionManager" />

<!--aspectj支援自動代理實現AOP功能 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

三、

在方法上增加 @Transactional 使其方法開始事務,注意方法是public的,另外方法裡面的事務別try cacth 掉,因為你處理了事務,事務就不會自動回滾,如果一定需要try catch 請捕獲後throw new RuntimeException(); 出來,否則事務也不會生效。