项目中经常遇到MyBatis与Spring的组合开发,并且相应的事务管理交给Spring。今天我这里记录一下Spring中Mybatis的事务管理。
先看代码:
spring-context.xml
1<?xml version="1.0" encoding="UTF-8"?> 2<beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 10 <!--开启注解--> 11 <context:annotation-config/> 12 <!--加载属性文件--> 13 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 14 <property name="locations"> 15 <list> 16 <value>classpath:db.properties</value> 17 </list> 18 </property> 19 </bean> 20 <!--扫描组建--> 21 <context:component-scan base-package="com.xwszt.txdemo"/> 22 <!--开启事务注解--> 23 <tx:annotation-driven transaction-manager="transactionManager"/> 24 25 <aop:aspectj-autoproxy proxy-target-class="true"/> 26 27 <!--配置数据源--> 28 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 29 <property name="driverClass" value="${jdbc.driver}"/> 30 <property name="jdbcUrl" value="${mysql.jdbc.url}"/> 31 <property name="user" value="${mysql.jdbc.user}"/> 32 <property name="password" value="${mysql.jdbc.password}"/> 33 <!--Connection Pooling Info --> 34 <property name="initialPoolSize" value="3"/> 35 <property name="minPoolSize" value="2"/> 36 <property name="maxPoolSize" value="15"/> 37 <property name="acquireIncrement" value="3"/> 38 <property name="maxStatements" value="8"/> 39 <property name="maxStatementsPerConnection" value="5"/> 40 <property name="maxIdleTime" value="1800"/> 41 <property name="autoCommitOnClose" value="false"/> 42 </bean> 43 44 <!--mybatis配置--> 45 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 46 <property name="dataSource" ref="dataSource"/> 47 <property name="mapperLocations" value="classpath:mapper/*"/> 48 </bean> 49 <!--mybatis扫描mapper对应类的配置--> 50 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 51 <property name="basePackage" value="com.xwszt.txdemo.dao"/> 52 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> 53 </bean> 54 <!--事务配置--> 55 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 56 <property name="dataSource" ref="dataSource"/> 57 </bean> 58</beans>
db.properties
1##mysql 2jdbc.driver=com.mysql.jdbc.Driver 3mysql.jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&useAffectedRows=true&allowPublicKeyRetrieval=true 4mysql.jdbc.user=root 5mysql.jdbc.password=*********(这里根据自己修改)
db.sql
1SET NAMES utf8mb4; 2SET FOREIGN_KEY_CHECKS = 0; 3 4-- ---------------------------- 5-- Table structure for user 6-- ---------------------------- 7DROP TABLE IF EXISTS `user`; 8CREATE TABLE `user` ( 9 `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 10 `username` varchar(50) DEFAULT NULL, 11 `password` varchar(50) DEFAULT NULL, 12 `salt` varchar(50) DEFAULT NULL, 13 `sex` varchar(10) DEFAULT NULL, 14 `address` varchar(50) DEFAULT NULL, 15 `cellphone` varchar(30) DEFAULT NULL, 16 `email` varchar(30) DEFAULT NULL, 17 `islock` smallint(1) unsigned NOT NULL DEFAULT '0', 18 `isvalidate` smallint(1) unsigned NOT NULL DEFAULT '1', 19 `isdel` smallint(1) unsigned NOT NULL DEFAULT '0', 20 PRIMARY KEY (`id`) 21) ENGINE=InnoDB AUTO_INCREMENT=124 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; 22 23SET FOREIGN_KEY_CHECKS = 1
UserDAO.xml
1<?xml version="1.0" encoding="UTF-8" ?> 2<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3<mapper namespace="com.xwszt.txdemo.dao.UserDAO"> 4 <insert id="insert" parameterType="com.xwszt.txdemo.entities.User"> 5 insert into `user` 6 (`id`, `username`, `password`, `salt`, `sex`, `address`, `cellphone`, `email`, `islock`,`isvalidate`,`isdel`) 7 values 8 (#{id}, #{username},#{password},#{salt},#{sex},#{address},#{cellphone},#{email},#{lock},#{validate},#{del}) 9 </insert> 10</mapper>
UserDAO.java
1package com.xwszt.txdemo.dao; 2 3import com.xwszt.txdemo.entities.User; 4 5public interface UserDAO { 6 void insert(User user); 7}
User.java
1package com.xwszt.txdemo.entities; 2 3import lombok.Data; 4 5import java.io.Serializable; 6 7@Data 8public class User implements Serializable { 9 private Long id; 10 private String username; 11 private String password; 12 private String salt; 13 private String sex; 14 private String address; 15 private String cellphone; 16 private String email; 17 private boolean lock; 18 private boolean validate; 19 private boolean del; 20}
UserService.java
1package com.xwszt.txdemo.service; 2 3public interface UserService { 4 void doSomething() throws Exception; 5 boolean saveUser() throws Exception; 6}
UserServiceImpl.java
1package com.xwszt.txdemo.service.impl; 2 3import com.xwszt.txdemo.dao.UserDAO; 4import com.xwszt.txdemo.entities.User; 5import com.xwszt.txdemo.service.UserService; 6import org.springframework.beans.factory.annotation.Autowired; 7import org.springframework.stereotype.Service; 8import org.springframework.transaction.annotation.Transactional; 9 10@Service 11public class UserServiceImpl implements UserService { 12 13 @Autowired 14 private UserService target; 15 16 @Autowired 17 private UserDAO userDAO; 18 19 @Override 20 public void doSomething() throws Exception { 21 target.saveUser(); 22 23 } 24 25 @Transactional 26 @Override 27 public boolean saveUser() throws Exception { 28 29 User user = new User(); 30 user.setId(123l); 31 user.setUsername("zhangsan"); 32 user.setPassword("123"); 33 user.setSalt("456"); 34 user.setSex("FEMAIL"); 35 user.setAddress("上海市张江高科"); 36 user.setCellphone("13582911229"); 37 user.setEmail("978732467@qq.com"); 38 user.setLock(false); 39 user.setValidate(true); 40 user.setDel(false); 41 42 userDAO.insert(user); 43 44 return true; 45 } 46}
UserTest.java
1package com.xwszt.txdemo; 2 3import com.xwszt.txdemo.service.UserService; 4import org.junit.Test; 5import org.junit.runner.RunWith; 6import org.springframework.beans.factory.annotation.Autowired; 7import org.springframework.test.context.ContextConfiguration; 8import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 9 10@RunWith(SpringJUnit4ClassRunner.class) 11@ContextConfiguration(locations = "classpath:spring-content.xml") 12public class UserTest { 13 14 @Autowired 15 private UserService userService; 16 17 @Test 18 public void saveUserTest() { 19 try { 20 userService.doSomething(); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } 24 } 25}
到此为止,代码已经贴完了。
那么,问题在哪儿呢?
在Service层,如果你仔细看,发现在service层saveUser方法上加了注解@Transactional,那么运行测试代码,不出意外(网络断了等)的情况下数据库里肯定会插入一条数据。
假如,我把@Transactional这个注解去掉了,也就是说saveUser不再使用spring的事务管理了,那么数据库里是不是没有插入数据呢?答案是否定的。数据库里依然会插入一条数据。
那这又是为什么呢?
如果使用Spring进行事务管理,这里提交的时候是Spring的事务管理commit了事务。
在没有使用Spring管理的事务时,是没有使用Spring容器管理的SqlSession提交了事务。
==================================================
接下来,一个新的问题。
在saveUser方法上使用了@Transactional注解,表明这个方法是Spring容器管理的事务,那么我在userDAO.insert(user);之后抛出异常,那么插入的数据会回滚吗?
1 @Transactional 2 @Override 3 public boolean saveUser() throws Exception { 4 5 User user = new User(); 6 user.setId(123l); 7 user.setUsername("zhangsan"); 8 user.setPassword("123"); 9 user.setSalt("456"); 10 user.setSex("FEMAIL"); 11 user.setAddress("上海市张江高科"); 12 user.setCellphone("13582911229"); 13 user.setEmail("978732467@qq.com"); 14 user.setLock(false); 15 user.setValidate(true); 16 user.setDel(false); 17 18 userDAO.insert(user); 19 20 if (true) { 21 throw new Exception("破坏性测试"); 22 } 23 return true; 24 }
答案是:不会回滚。
那怎样才会回滚呢?配置rollback即可。即:
@Transactional(rollbackFor = Exception.class)