1. 程式人生 > >mybatis整合spring、springmvc時業務層無法進行事務回滾問題解決

mybatis整合spring、springmvc時業務層無法進行事務回滾問題解決

前言:近期換了新公司,剛來公司就接觸了一下mybatis,因為springmvc和spring比較熟悉,我想大概現在絕大部分的公司都在用吧,剛接觸mybatis時感覺真心蛋疼,純sql才處理業務,實在是有點不習慣,不過感覺整個框架較之前的orm架構確實感覺速度快一點。

好了,直接進入正題

需求:需要在一個業務層方法內完成對兩張不同的表進行插入操作

一開始我直接在mybatis的配置檔案中想寫兩條sql語句,兩條sql語句已“;”隔開,不過沒成功,網上查了一下資料說mybatis不支援這樣的,這條路行不通之後顯然就只剩下另外一條路了:在業務層的某個方法中呼叫兩次dao的,對兩張不同的表進行插入操作。

此方式可行:

public void method(Param param) throws Exception {
		dao.save("xxx.save", param);
		dao.save("yyy.save", param);
	}
但是如果這種方式需要考慮事務問題,於是在兩個方法之間丟擲一個異常準備試一試事務機制
public void method(Param param) throws Exception {
		dao.save("xxx.save", param);
		int a = 1/0;
		dao.save("yyy.save", param);
	}
不試不知道,一試了一下,果然沒有進行回滾

以下是dao的程式碼:

@Repository("daoSupport")
public class DaoSupport implements Dao {

	@Resource(name = "sqlSessionTemplate")
	private SqlSessionTemplate sqlSessionTemplate;
	
	
	public Object save(String str, Object obj) throws Exception {
		return sqlSessionTemplate.insert(str, obj);
	}
}
在網上查了很多資料,都沒有什麼找到解決方案,所有的配置檔案都正常

spring配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/aop 
						http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context-3.0.xsd
						http://www.springframework.org/schema/tx 
						http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	">
	
	<!-- 啟用註解 -->
	<context:annotation-config />
	
	<!-- 啟動元件掃描,排除@Controller元件,該元件由SpringMVC配置檔案掃描 -->
	<context:component-scan base-package="com.???">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
    	<property name="dataSource" ref="dataSource"></property>
 	</bean>
	
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
		<property name="locations">  
			<list>  
                 <value>/WEB-INF/classes/dbconfig.properties</value>  
            </list>  
        </property>  
	</bean> 
	
	<!-- 阿里 druid資料庫連線池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">  
         <!-- 資料庫基本資訊配置 -->
         <property name="url" value="${url}" />  
         <property name="username" value="${username}" />  
         <property name="password" value="${password}" />  
         <property name="driverClassName" value="${driverClassName}" />  
         <property name="filters" value="${filters}" />  
   		 <!-- 最大併發連線數 -->
         <property name="maxActive" value="${maxActive}" />
         <!-- 初始化連線數量 -->
         <property name="initialSize" value="${initialSize}" />
         <!-- 配置獲取連線等待超時的時間 -->
         <property name="maxWait" value="${maxWait}" />
         <!-- 最小空閒連線數 -->
         <property name="minIdle" value="${minIdle}" />  
   		 <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->
         <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
         <!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->
         <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />  
         <property name="validationQuery" value="${validationQuery}" />  
         <property name="testWhileIdle" value="${testWhileIdle}" />  
         <property name="testOnBorrow" value="${testOnBorrow}" />  
         <property name="testOnReturn" value="${testOnReturn}" />  
         <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
         <!-- 開啟removeAbandoned功能 -->
         <property name="removeAbandoned" value="${removeAbandoned}" />
         <!-- 1800秒,也就是30分鐘 -->
         <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
         <!-- 關閉abanded連線時輸出錯誤日誌 -->   
         <property name="logAbandoned" value="${logAbandoned}" />
	</bean>  
	
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="delete*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception"/>
			<tx:method name="insert*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception" />
			<tx:method name="update*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception" />
			<tx:method name="save*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception" />
		</tx:attributes>
	</tx:advice>
	
	<aop:aspectj-autoproxy proxy-target-class="true"/>
	
	<!-- 事物處理 -->
	<aop:config>
		<aop:pointcut id="pc" expression="execution(* xxx..*(..))" />
		<aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
	</aop:config>
	
	<!-- 配置mybatis -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <!-- mapper掃描 -->
        <property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property>
    </bean>
    
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactory" />
	</bean>
	
	<!-- ================ Shiro start ================ -->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="ShiroRealm" />
		</bean>
		
		<!-- 專案自定義的Realm -->
	    <bean id="ShiroRealm" class="com.???.basic.interceptor.shiro.ShiroRealm" ></bean>
		
		<!-- Shiro Filter -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<property name="securityManager" ref="securityManager" />
			
			<property name="loginUrl" value="/" />
			
			<property name="successUrl" value="/main/index" />
			
			<property name="unauthorizedUrl" value="/login_toLogin" />
			
			<property name="filterChainDefinitions">
				<value>
				/wap/**/**          = anon
				/static/login/** 	= anon
				/static/js/myjs/** 	= authc
				/static/js/** 		= anon
				/static/wap/**      = anon
	           	/code.do 			= anon
	           	/login_login	 	= anon
	           	/app**/** 			= anon
	           	/weixin/** 			= anon
	           	/**					= authc
				</value>
			</property>
		</bean>
</beans>

springmvc配置檔案:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd	
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<mvc:annotation-driven/>	
	<mvc:default-servlet-handler/>
	
	<context:component-scan base-package="com.xxx" />

	<!-- 對靜態資原始檔的訪問  restful-->     
	<mvc:resources mapping="/admin/**" location="/,/admin/" />
	<mvc:resources mapping="/static/**" location="/,/static/" />
	<mvc:resources mapping="/plugins/**" location="/,/plugins/" />
	<mvc:resources mapping="/uploadFiles/**" location="/,/uploadFiles/" /> 

	<!-- 訪問攔截  -->  
  	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**/**"/>
			<bean class="com.xxx.basic.interceptor.LoginHandlerInterceptor"/>
		</mvc:interceptor>
	</mvc:interceptors>
	 
	<!-- 配置SpringMVC的檢視解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
	<bean id="exceptionResolver" class="com.???.basic.resolver.MyExceptionResolver"></bean>
	<!-- 上傳攔截,如最大上傳值及最小上傳值 -->
	  <bean id="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >   
		  <property name="maxUploadSize">    
	          <value>104857600</value>    
	       </property>   
	        <property name="maxInMemorySize">    
	            <value>4096</value>    
	        </property>   
	         <property name="defaultEncoding">    
	            <value>utf-8</value>    
	        </property> 
    </bean>  
</beans>


後來在網上看到了這個,試了以下,果然解決了點選開啟連結

解決方案:修改springmvc配置檔案,

修改內容:

<!-- 啟動元件掃描,排除@Service元件,注:如果此處必須排除掉@Service元件 
原因:springmvc的配置檔案與spring的配置檔案不是同時載入,如果這邊不進行這樣的設定,
那麼,spring就會將所有帶@Service註解的類都掃描到容器中,
等到載入spring的配置檔案的時候,會因為容器已經存在Service類,
使得cglib將不對Service進行代理,直接導致的結果就是在spring配置檔案中的事務配置不起作用,發生異常時,無法對資料進行回滾 
-->
<context:component-scan base-package="com.???">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd	
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<mvc:annotation-driven/>	
	<mvc:default-servlet-handler/>

	<strong><span style="color:#ff0000;"><!-- 啟動元件掃描,排除@Service元件,注:如果此處必須排除掉@Service元件 
	原因:springmvc的配置檔案與spring的配置檔案不是同時載入,如果這邊不進行這樣的設定,
	那麼,spring就會將所有帶@Service註解的類都掃描到容器中,
	等到載入spring的配置檔案的時候,會因為容器已經存在Service類,
	使得cglib將不對Service進行代理,直接導致的結果就是在spring配置檔案中的事務配置不起作用,發生異常時,無法對資料進行回滾 
	--></span></strong>
	<context:component-scan base-package="com.xxx">
	<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Service" />
	</context:component-scan></strong></span>

	<!-- 對靜態資原始檔的訪問  restful-->     
	<mvc:resources mapping="/admin/**" location="/,/admin/" />
	<mvc:resources mapping="/static/**" location="/,/static/" />
	<mvc:resources mapping="/plugins/**" location="/,/plugins/" />
	<mvc:resources mapping="/uploadFiles/**" location="/,/uploadFiles/" /> 

	<!-- 訪問攔截  -->  
  	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**/**"/>
			<bean class="com.xxx.basic.interceptor.LoginHandlerInterceptor"/>
		</mvc:interceptor>
	</mvc:interceptors>
	 
	<!-- 配置SpringMVC的檢視解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
	<bean id="exceptionResolver" class="com.???.basic.resolver.MyExceptionResolver"></bean>
	<!-- 上傳攔截,如最大上傳值及最小上傳值 -->
	  <bean id="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >   
		  <property name="maxUploadSize">    
	          <value>104857600</value>    
	       </property>   
	        <property name="maxInMemorySize">    
	            <value>4096</value>    
	        </property>   
	         <property name="defaultEncoding">    
	            <value>utf-8</value>    
	        </property> 
    </bean>  
</beans>

修改後重啟tomcat後就有事務了!!!!,感恩 感恩!~~~

總結:如果spring和springmvc整合的時候,兩個配置檔案各自掃描自己的類,mvc配置檔案就掃描controller,不掃描其他的,而spring配置檔案件不掃描controller,掃描其他的。

備註:我之前一個專案是將事務的配置配置在springmvc的配置檔案當中,兩個配置檔案都掃描全部,所以不會有問題