终极办法:解决spring mvc+mysql+mybatis事务不提交不回滚的问题

来源:互联网 发布:网络管理软件哪个好 编辑:程序博客网 时间:2024/05/20 05:05

网上逛了一大圈,终于解决了,我是网文搬运工,把我解决的过程放出来供大家参考。

首先:要确定你的数据库是否是支持事务,并且一定要关闭连接池的auto-commit自动提交功能,再往下看

一:事务使用。


先来一个普级稿,几种事务的配置方法:

1. myBatis单独使用时,使用SqlSession来处理事务

Java代码  收藏代码
  1. public class MyBatisTxTest {  
  2.   
  3.     private static SqlSessionFactory sqlSessionFactory;  
  4.     private static Reader reader;  
  5.   
  6.     @BeforeClass  
  7.     public static void setUpBeforeClass() throws Exception {  
  8.         try {  
  9.             reader = Resources.getResourceAsReader("Configuration.xml");  
  10.             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);  
  11.         } finally {  
  12.             if (reader != null) {  
  13.                 reader.close();  
  14.             }  
  15.         }  
  16.     }  
  17.       
  18.     @Test  
  19.     public void updateUserTxTest() {  
  20.         SqlSession session = sqlSessionFactory.openSession(false); // 打开会话,事务开始  
  21.           
  22.         try {  
  23.             IUserMapper mapper = session.getMapper(IUserMapper.class);  
  24.             User user = new User(9"Test transaction");  
  25.             int affectedCount = mapper.updateUser(user); // 因后面的异常而未执行commit语句  
  26.             User user = new User(10"Test transaction continuously");  
  27.             int affectedCount2 = mapper.updateUser(user2); // 因后面的异常而未执行commit语句  
  28.             int i = 2 / 0// 触发运行时异常  
  29.             session.commit(); // 提交会话,即事务提交  
  30.         } finally {  
  31.             session.close(); // 关闭会话,释放资源  
  32.         }  
  33.     }  
  34. }  


2. 和Spring集成后,使用Spring的事务管理:

a. @Transactional方式:

在类路径下创建beans-da-tx.xml文件,在beans-da.xml(系列五)的基础上加入事务配置:
Xml代码  收藏代码
  1. <!-- 事务管理器 -->  
  2. <bean id="txManager"  
  3.     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  4.         <property name="dataSource" ref="dataSource" />  
  5. </bean>  
  6.   
  7. <!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 -->  
  8. <tx:annotation-driven transaction-manager="txManager" />  
  9.   
  10. <bean id="userService" class="com.john.hbatis.service.UserService" />  


服务类:
Java代码  收藏代码
  1. @Service("userService")  
  2. public class UserService {  
  3.   
  4.     @Autowired  
  5.     IUserMapper mapper;  
  6.   
  7.     public int batchUpdateUsersWhenException() { // 非事务性  
  8.         User user = new User(9"Before exception");  
  9.         int affectedCount = mapper.updateUser(user); // 执行成功  
  10.         User user2 = new User(10"After exception");  
  11.         int i = 1 / 0// 抛出运行时异常  
  12.         int affectedCount2 = mapper.updateUser(user2); // 未执行  
  13.         if (affectedCount == 1 && affectedCount2 == 1) {  
  14.             return 1;  
  15.         }  
  16.         return 0;  
  17.     }  
  18.   
  19.     @Transactional  
  20.     public int txUpdateUsersWhenException() { // 事务性  
  21.         User user = new User(9"Before exception");  
  22.         int affectedCount = mapper.updateUser(user); // 因后面的异常而回滚  
  23.         User user2 = new User(10"After exception");  
  24.         int i = 1 / 0// 抛出运行时异常,事务回滚  
  25.         int affectedCount2 = mapper.updateUser(user2); // 未执行  
  26.         if (affectedCount == 1 && affectedCount2 == 1) {  
  27.             return 1;  
  28.         }  
  29.         return 0;  
  30.     }  
  31. }  


在测试类中加入:
Java代码  收藏代码
  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations = { "classpath:beans-da-tx.xml" })  
  3. public class SpringIntegrateTxTest {  
  4.   
  5.     @Resource  
  6.     UserService userService;  
  7.   
  8.     @Test  
  9.     public void updateUsersExceptionTest() {  
  10.         userService.batchUpdateUsersWhenException();  
  11.     }  
  12.   
  13.     @Test  
  14.     public void txUpdateUsersExceptionTest() {  
  15.         userService.txUpdateUsersWhenException();  
  16.     }  
  17. }  


b. TransactionTemplate方式

在beans-da-tx.xml中添加:
Xml代码  收藏代码
  1. <bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">  
  2.     <constructor-arg type="org.springframework.transaction.PlatformTransactionManager" ref="transactionManager" />  
  3. </bean>  


在UserService类加入:
Java代码  收藏代码
  1. @Autowired(required = false)  
  2. TransactionTemplate txTemplate;  
  3.   
  4. public int txUpdateUsersWhenExceptionViaTxTemplate() {  
  5.     int retVal = txTemplate.execute(new TransactionCallback<Integer>() {  
  6.   
  7.         @Override  
  8.         public Integer doInTransaction(TransactionStatus status) { // 事务操作  
  9.             User user = new User(9"Before exception");  
  10.             int affectedCount = mapper.updateUser(user); // 因后面的异常而回滚  
  11.             User user2 = new User(10"After exception");  
  12.             int i = 1 / 0// 抛出运行时异常并回滚  
  13.             int affectedCount2 = mapper.updateUser(user2); // 未执行  
  14.             if (affectedCount == 1 && affectedCount2 == 1) {  
  15.                 return 1;  
  16.             }  
  17.             return 0;  
  18.         }  
  19.           
  20.     });  
  21.     return retVal;  
  22. }  


在SpringIntegrateTxTest类中加入:
Java代码  收藏代码
  1. @Test  
  2. public void updateUsersWhenExceptionViaTxTemplateTest() {  
  3.     userService.txUpdateUsersWhenExceptionViaTxTemplate(); //   
  4. }  


注:不可catch ExceptionRuntimeException而不抛出
Java代码  收藏代码
  1. @Transactional  
  2. public int txUpdateUsersWhenExceptionAndCatch() { // 事务性操作,但是外围框架捕获不到异常,认为执行正确而提交。  
  3.     try {  
  4.         User user = new User(9"Before exception");  
  5.         int affectedCount = mapper.updateUser(user); // 执行成功  
  6.         User user2 = new User(10"After exception");  
  7.         int i = 1 / 0// 抛出运行时异常  
  8.         int affectedCount2 = mapper.updateUser(user2); // 未执行  
  9.         if (affectedCount == 1 && affectedCount2 == 1) {  
  10.             return 1;  
  11.         }  
  12.     } catch (Exception e) { // 所有异常被捕获而未抛出  
  13.         e.printStackTrace();  
  14.     }  
  15.     return 0;  



二:相关知识

ContextLoaderListener和Spring MVC中的DispatcherServlet加载内容的区别

一:ContextLoaderListener加载内容

  

二:DispatcherServlt加载内容

  

  ContextLoaderListener和DispatcherServlet都会在Web容器启动的时候加载一下bean配置. 区别在于:

  DispatcherServlet一般会加载MVC相关的bean配置管理(如: ViewResolver, Controller, MultipartResolver, ExceptionHandler, etc.)

  ContextLoaderListener一般会加载整个Spring容器相关的bean配置管理(如: Log, Service, Dao, PropertiesLoader, etc.)

  DispatcherServlet默认使用WebApplicationContext作为上下文.

  值得注意的是, DispatcherServlet的上下文仅仅是Spring MVC的上下文, 而ContextLoaderListener的上下文则对整个Spring都有效. 一般Spring web项目中同时会使用这两种上下文.


三、正确的配置事务

配置Spring声明式事务,执行中出现异常未回滚.从网上查询得到一开始是自己的配置出了问题,由于配置文件的加载顺序决定了容器的加载顺序导致Spring事务没有起作用。详情如下:

由于采用的是SpringMVC、 MyBatis,故统一采用了标注来声明Service、Controller
由于服务器启动时的加载配置文件的顺序为web.xml—root-context.xml(Spring的配置文件)—servlet-context.xml(SpringMVC的配置文件),由于root-context.xml配置文件中Controller会先进行扫描装配,但是此时service还没有进行事务增强处理,得到的将是原样的Service(没有经过事务加强处理,故而没有事务处理能力),所以我们必须在root-context.xml中不扫描Controller

上面的问题解决后还是没有回滚,后来了解到,Spring 只会在程序执行中出现unchecked(RuntimeException)的异常时才会触发回滚。由于是与客户端直接交互的Server所以要将每一个处理结果以 errorcode 错误码和msg 错误信息的形式反馈给客户端所以显式捕捉了所有的异常,并将信息以Json数据格式发送给客户端这才导致了出现异常时事务没有回滚。

因为要给客户端最真实、准确的错误信息反馈又不得不捕捉可能发生的异常又陷入了沉思.当然,问题总是有解决的方式的,哪怕是绕着走。之后从查询资料得到,捕捉可以,但是捕捉之后主动抛出还是会引发事务回滚的!(喜)然后就想到在主动 throw new RuntimeException(“反馈给客户端的信息”);将要反馈给客户端的具体错误信息包装到异常信息中,发生异常时在Controller层catch异常,将信息返回至客户端。
(mysql 表的engine为InnoDB–支持事务回滚,默认为MyISAM–效率高)
到此,问题解决。

案例声明

岗位: Java服务端

工作内容: 接收来自客户端的请求(android,androidtv,ios,pc ..),对客户端请求数据做合法性校验,并与其他服务端交互获取客户端所需数据。

代码及配置

1.web.xml配置

<?xml version="1.0" encoding="UTF-8"?><listener><listener-class>        org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value>  </context-param>  <servlet><servlet-name>spring-mvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:springmvc-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup>  </servlet>

2. Spring-servlet.xml配置

<?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:p="http://www.springframework.org/schema/p"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop"     xmlns:tx="http://www.springframework.org/schema/tx"     xmlns:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="    http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-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/aop   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd     http://www.springframework.org/schema/tx      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd      http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><!-- 配置注解扫描,扫描 Controller层不扫描Service层 -->    <context:component-scan base-package="cn.com.XX">        <context:include-filter type="annotation"            expression="org.springframework.stereotype.Controller" />        <context:exclude-filter type="annotation"            expression="org.springframework.stereotype.Service" />    </context:component-scan></beans>  

3. mybatis-config.xml配置

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <settings>        <!-- changes from the defaults for testing -->        <setting name="cacheEnabled" value="true" />        <setting name="useGeneratedKeys" value="true" />        <setting name="defaultExecutorType" value="REUSE" />        <!-- <setting name="logImpl" value="LOG4J"/> -->    </settings>    <!-- mybatis分页插件 -->    <plugins>        <plugin interceptor="com.github.pagehelper.PageHelper">            <property name="dialect" value="mysql" />        </plugin>    </plugins></configuration>

4. applicationContext.xml配置

<?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:p="http://www.springframework.org/schema/p"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:aop="http://www.springframework.org/schema/aop"     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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.xsd http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd  ">    <!--加载配置文件 -->    <bean id="propertyConfigurer"        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">        <property name="location" value="classpath:system.properties" />    </bean>    <!--配置数据源 -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="com.mysql.jdbc.Driver">        </property>        <property name="jdbcUrl"            value="${数据库连接}">        </property>        <property name="user" value="root"></property>        <property name="password" value="root"></property>        <!--连接池中保留的最大连接数。Default: 15 -->        <property name="maxPoolSize" value="15"></property>        <!--连接池中保留的最小连接数。 -->        <property name="minPoolSize" value="3"></property>        <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->        <property name="initialPoolSize" value="3"></property>        <!--最大空闲时间,20秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->        <property name="maxIdleTime" value="20"></property>        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->        <property name="acquireIncrement">            <value>5</value>        </property>        <!-- JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。             如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->        <property name="maxStatements">            <value>0</value>        </property>        <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->        <property name="idleConnectionTestPeriod">            <value>60</value>        </property>        <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->        <property name="acquireRetryAttempts">            <value>30</value>        </property>        <!-- 获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试             获取连接失败后该数据源将申明已断开并永久关闭。Default: false -->        <property name="breakAfterAcquireFailure">            <value>true</value>        </property>        <!-- 因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable             等方法来提升连接测试的性能。Default: false -->        <property name="testConnectionOnCheckout">            <value>true</value>        </property>    </bean>    <!-- 注解扫描,不扫描Controller层 -->    <context:component-scan base-package="cn.com.xx">        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>    </context:component-scan>    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="configLocation" value="classpath:mybatis-config.xml" />        <property name="mapperLocations" value="classpath:cn/com/xx/**/*.xml" />    </bean>    <!-- yxt add -->    <bean id="mapperScanneryxt" class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="basePackage" value="cn.com.xx.mapper" />    </bean>    <!--配置事务管理器 -->    <!-- transaction manager, use DataSourceTransactionManager -->    <bean id="txManager"        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource" />    </bean>    <!-- 切面 -->    <aop:config>        <aop:pointcut id="fooServiceMethods"            expression="execution(* cn.com.xx.service.*.*(..))" />        <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceMethods" />    </aop:config>    <!--通知 -->    <tx:advice id="txAdvice" transaction-manager="txManager">        <tx:attributes>            <tx:method name="select*" read-only="true" />            <tx:method name="*" rollback-for="Exception" />        </tx:attributes>    </tx:advice></beans>

5. 代码示例

Service业务逻辑处理层

try {    log.info("check phone is exist before ..");    int count = tMailingMapper.insert(record);        if (count > 0) {                log.info("添加 " + accountid + " 的好友"                        + account.getAccountid() + "  "                        + phoneVo.getRemark() + "  成功");        } else {                log.info("添加 " + accountid + " 的好友"                        + account.getAccountid() + "  "                        + phoneVo.getRemark() + "  失败");        }} catch (Exception e) {    log.error("添加联系人出现了异常 " + e.getMessage());    resJson.put("errorcode", "20022");    resJson.put("msg", "同步信息异常,请稍后重试");    throw new RuntimeException(resJson.toString());}

Controller 控制层

@RequestMapping("/update/userinfo")    public String updateUserInfo(HttpServletRequest request, HttpServletResponse response) {        log.info("update userInfo start ..");        String resText=null;        try {            resText = userService.updateUserInfo(request);        } catch (Exception e) {            log.error("更新信息失败,事务已回滚...",e);            resText=e.getMessage();        }        <-- 将操作结果返回给client-->        HttpsUtil.sendAppMessage(resText, response);        return null;    }

文档连接:

ContextLoaderListener和Spring MVC中的DispatcherServlet加载内容的区别


springmvc mybatis 声明式事务管理回滚失效,(checked回滚)捕捉异常,传输错误信息


myBatis系列之七:事务管理



阅读全文
0 0