mybatis整合spring、springmvc时业务层无法进行事务回滚问题解决

1 篇文章 0 订阅
1 篇文章 0 订阅

前言:近期换了新公司,刚来公司就接触了一下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的配置文件当中,两个配置文件都扫描全部,所以不会有问题





  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring Boot MyBatis 整合可以使用以下步骤: 1. 新建一个 Spring Boot 项目,并添加 MyBatisSpring MVC 的依赖。 ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 配置 MyBatis 的数据源和 SQLSessionFactory。 ```java @Configuration @MapperScan("com.example.demo.mapper") public class MybatisConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return new DruidDataSource(); } @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); return sessionFactory.getObject(); } } ``` 3. 编写 Mapper 接口和对应的 XML 映射文件。 ```java public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User getUserById(@Param("id") Integer id); } ``` ```xml <mapper namespace="com.example.demo.mapper.UserMapper"> <select id="getUserById" resultType="com.example.demo.entity.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper> ``` 4. 在 Controller 中注入 Mapper 并使用。 ```java @RestController public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/user/{id}") public User getUserById(@PathVariable Integer id) { return userMapper.getUserById(id); } } ``` 以上就是 Spring Boot MyBatis 整合的基本步骤。需要注意的是,在使用 MyBatis ,需要在 Mapper 接口上添加 `@Mapper` 注解或使用 `@MapperScan` 注解指定 Mapper 接口所在的包。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值