MyBatis5中Spring集成MyBatis事物管理
单独使用MyBatis对事物进行管理
前面MyBatis的文章有写过相关内容,这里继续写一个最简单的Demo,算是复习一下之前MyBatis的内容吧,先是建表,建立一个简单的Student表:
createtablestudent ( student_idintauto_increment, student_namevarchar(20)notnull, primarykey(student_id) )
建立实体类Student.java:
publicclassStudent { privateintstudentId; privateStringstudentName; publicintgetStudentId() { returnstudentId; } publicvoidsetStudentId(intstudentId) { this.studentId=studentId; } publicStringgetStudentName() { returnstudentName; } publicvoidsetStudentName(StringstudentName) { this.studentName=studentName; } publicStringtoString() { return"Student{[studentId:"+studentId+"],[studentName:"+studentName+"]}"; } }
多说一句,对实体类重写toString()方法,打印其中每一个(或者说是关键属性)是一个推荐的做法。接着是config.xml,里面是jdbc基本配置:
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAliasalias="Student"type="org.xrq.domain.Student"/> </typeAliases> <environmentsdefault="development"> <environmentid="development"> <transactionManagertype="JDBC"/> <dataSourcetype="POOLED"> <propertyname="driver"value="com.mysql.jdbc.Driver"/> <propertyname="url"value="jdbc:mysql://localhost:3306/test"/> <propertyname="username"value="root"/> <propertyname="password"value="root"/> </dataSource> </environment> </environments> <mappers> <mapperresource="student_mapper.xml"/> </mappers> </configuration>
然后是student_mapper.xml,主要是具体的sql语句:
<mappernamespace="StudentMapper"> <resultMaptype="Student"id="StudentMap"> <idcolumn="student_id"property="studentId"jdbcType="INTEGER"/> <resultcolumn="student_name"property="studentName"jdbcType="VARCHAR"/> </resultMap> <selectid="selectAllStudents"resultMap="StudentMap"> selectstudent_id,student_namefromstudent; </select> <insertid="insertStudent"useGeneratedKeys="true"keyProperty="studentId"parameterType="Student"> insertintostudent(student_id,student_name)values(#{studentId,jdbcType=INTEGER},#{studentName,jdbcType=VARCHAR}); </insert> </mapper>
建立一个MyBatisUtil.java,用于建立一些MyBatis基本元素的,后面的类都继承这个类:
publicclassMyBatisUtil { protectedstaticSqlSessionFactoryssf; protectedstaticReaderreader; static { try { reader=Resources.getResourceAsReader("config.xml"); ssf=newSqlSessionFactoryBuilder().build(reader); } catch(IOExceptione) { e.printStackTrace(); } } protectedSqlSessiongetSqlSession() { returnssf.openSession(); } }
企业级开发讲求:
1、定义和实现分开
2、分层开发,通常情况下为Dao-->Service-->Controller,不排除根据具体情况多一层/几层或少一层
所以,先写一个StudentDao.java接口:
publicinterfaceStudentDao { publicList<Student>selectAllStudents(); publicintinsertStudent(Studentstudent); }
最后写一个StudentDaoImpl.java实现这个接口,注意要继承MyBatisUtil.java类:
publicclassStudentDaoImplextendsMyBatisUtilimplementsStudentDao { privatestaticfinalStringNAMESPACE="StudentMapper."; publicList<Student>selectAllStudents() { SqlSessionss=getSqlSession(); List<Student>list=ss.selectList(NAMESPACE+"selectAllStudents"); ss.close(); returnlist; } publicintinsertStudent(Studentstudent) { SqlSessionss=getSqlSession(); inti=ss.insert(NAMESPACE+"insertStudent",student); //ss.commit(); ss.close(); returni; } }
写一个测试类:
publicclassStudentTest { publicstaticvoidmain(String[]args) { StudentDaostudentDao=newStudentDaoImpl(); Studentstudent=newStudent(); student.setStudentName("Jack"); studentDao.insertStudent(student); System.out.println("插入的主键为:"+student.getStudentId()); System.out.println("-----Displaystudents------"); List<Student>studentList=studentDao.selectAllStudents(); for(inti=0,length=studentList.size();i<length;i++) System.out.println(studentList.get(i)); } }
结果一定是空。
我说过这个例子既是作为复习,也是作为一个引子引入我们今天的内容,空的原因是,insert操作已经做了,但是MyBatis并不会帮我们自动提交事物,所以展示出来的自然是空的。这种时候就必须手动通过SqlSession的commit()方法提交事务,即打开StudentDaoImpl.java类第17行的注释就可以了。
多说一句,这个例子除了基本的MyBatis插入操作之外,在插入的基础上还有返回插入的主键id的功能。
接下来,就利用Spring管理MyBatis事物,这也是企业级开发中最常用的事物管理做法。
使用Spring管理MyBatis事物
关于这块,网上有很多文章讲解,我搜索了很多,但是要么就是相互复制黏贴,要么就是没有把整个例子讲清楚的,通过这一部分,我尽量讲清楚如何使用Spring管理MyBatis事物。
使用Spring管理MyBatis事物,除了Spring必要的模块beans、context、core、expression、commons-logging之外,还需要以下内容:
(1)MyBatis-Spring-1.x.0.jar,这个是Spring集成MyBatis必要的jar包
(2)数据库连接池,dbcp、c3p0都可以使用,我这里使用的是阿里的druid
(3)jdbc、tx、aop,jdbc是基本的不多说,用到tx和aop是因为Spring对MyBatis事物管理的支持是通过aop来实现的
(4)aopalliance.jar,这个是使用SpringAOP必要的一个jar包
上面的jar包会使用Maven的可以使用Maven下载,没用过Maven的可以去CSDN上下载,一搜索就有的。
MyBatis的配置文件config.xml里面,关于jdbc连接的部分可以都去掉,只保留typeAliases的部分:
<?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAliasalias="Student"type="org.xrq.domain.Student"/> </typeAliases> </configuration>
多提一句,MyBatis另外一个配置文件student_mapper.xml不需要改动。接着,写Spring的配置文件,我起名字叫做spring.xml:
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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/beanshttp://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/jdbchttp://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> <!--注解配置--> <tx:annotation-driventransaction-manager="transactionManager"/> <context:annotation-config/> <context:component-scanbase-package="org.xrq"/> <!--数据库连接池,这里使用alibaba的Druid--> <beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource"init-method="init"destroy-method="close"> <propertyname="url"value="jdbc:mysql://localhost:3306/test"/> <propertyname="username"value="root"/> <propertyname="password"value="root"/> </bean> <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"> <propertyname="configLocation"value="classpath:config.xml"/> <propertyname="mapperLocations"value="classpath:*_mapper.xml"/> <propertyname="dataSource"ref="dataSource"/> </bean> <!--事务管理器--> <beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <propertyname="dataSource"ref="dataSource"/> </bean> </beans>
这里面主要就是事务管理器和数据库连接池两部分的内容。
另外我们看到有一个SqlSessionFactory,使用过MyBatis的朋友们一定对这个类不陌生,它是用于配置MyBatis环境的,SqlSessionFactory里面有两个属性configLocation、mapperLocations,顾名思义分别代表配置文件的位置和映射文件的位置,这里只要路径配置正确,Spring便会自动去加载这两个配置文件了。
然后要修改的是Dao的实现类,此时不再继承之前的MyBatisUtil这个类,而是继承MyBatis-Spring-1.x.0.jar自带的SqlSessionDaoSupport.java,具体代码如下:
@Repository publicclassStudentDaoImplextendsSqlSessionDaoSupportimplementsStudentDao { privatestaticfinalStringNAMESPACE="StudentMapper."; @Resource publicvoidsetSqlSessionFactory(SqlSessionFactorysqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); } publicList<Student>selectAllStudents() { returngetSqlSession().selectList(NAMESPACE+"selectAllStudents"); } publicintinsertStudent(Studentstudent) { returngetSqlSession().insert(NAMESPACE+"insertStudent",student); } }
这里用到了两个注解,分别说一下。
(1)@Repository,这个注解和@Component、@Controller和我们最常见的@Service注解是一个作用,都可以将一个类声明为一个Spring的Bean。它们的区别到不在于具体的语义上,更多的是在于注解的定位上。之前说过,企业级应用注重分层开发的概念,因此,对这四个相似的注解应当有以下的理解:
•@Repository注解,对应的是持久层即Dao层,其作用是直接和数据库交互,通常来说一个方法对应一条具体的Sql语句
•@Service注解,对应的是服务层即Service层,其作用是对单条/多条Sql语句进行组合处理,当然如果简单的话就直接调用Dao层的某个方法了
•@Controller注解,对应的是控制层即MVC设计模式中的控制层,其作用是接收用户请求,根据请求调用不同的Service取数据,并根据需求对数据进行组合、包装返回给前端
•@Component注解,这个更多对应的是一个组件的概念,如果一个Bean不知道属于拿个层,可以使用@Component注解标注
这也体现了注解的其中一个优点:见名知意,即看到这个注解就大致知道这个类的作用即它在整个项目中的定位。
(2)@Resource,这个注解和@Autowired注解是一个意思,都可以自动注入属性属性。由于SqlSessionFactory是MyBatis的核心,它在spring.xml中又进行过了声明,因此这里通过@Resource注解将id为"sqlSessionFactory"的Bean给注入进来,之后就可以通过getSqlSession()方法获取到SqlSession并进行数据的增、删、改、查了。
最后无非就是写一个测试类测试一下:
publicclassStudentTest { publicstaticvoidmain(String[]args) { ApplicationContextac=newClassPathXmlApplicationContext("spring.xml"); StudentDaostudentDao=(StudentDao)ac.getBean("studentDaoImpl"); Studentstudent=newStudent(); student.setStudentName("Lucy"); intj=studentDao.insertStudent(student); System.out.println("j="+j+"\n"); System.out.println("-----Displaystudents------"); List<Student>studentList=studentDao.selectAllStudents(); for(inti=0,length=studentList.size();i<length;i++) System.out.println(studentList.get(i)); } }
由于StudentDaoImpl.java类使用了@Repository注解且没有指定别名,因此StudentDaoImpl.java在Spring容器中的名字为"首字母小写+剩余字母"即"studentDaoImpl"。
运行一下程序,可以看见控制台上遍历出了new出来的Student,即该Student直接被插入了数据库中,整个过程中没有任何的commit、rollback,全部都是由Spring帮助我们实现的,这就是利用Spring对MyBatis进行事物管理。
后记
本文复习了MyBatis的基本使用与使用Spring对MyBatis进行事物管理,给出了比较详细的代码例子,有需要的朋友们可以照着代码研究一下。在本文的基础上,后面还会写一篇文章,讲解一下多数据在单表和多表之间的事物管理实现,这种需求也是属于企业及应用中比较常见的需求。