单独使用mybatis是有很多限制的(比如无法实现跨越多个session的事务),而且很多业务系统本来就是使用spring来管理的事务,因此mybatis最好与spring集成起来使用。
版本要求
项目 |
版本 |
下载地址 |
说明 |
mybatis |
3.0及以上 |
https://github.com/mybatis/mybatis-3/releases |
|
spring |
3.0及以上 |
http://projects.spring.io/spring-framework/ |
|
mybatis-spring |
1.0及以上 |
https://github.com/mybatis/spring/releases |
|
spring事务配置
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!-- 自动扫描业务包 --> < context:component-scan base-package = "com.xxx.service" /> <!-- 数据源 --> < jee:jndi-lookup id = "jndiDataSource" jndi-name = "java:comp/env/jdbc/datasource" /> <!-- 配置事务 --> < bean id = "txManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" > < property name = "dataSource" ref = "jndiDataSource" /> </ bean > <!-- 配置基于注解的事物aop --> < tx:annotation-driven transaction-manager = "txManager" proxy-target-class = "true" /> |
单个集成
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!-- 集成mybatis --> < bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" > < property name = "dataSource" ref = "jndiDataSource" /> < property name = "configLocation" value = "classpath:/mybatis/mybatis-config.xml" /> <!-- 自动配置别名 --> < property name = "typeAliasesPackage" value = "com.xxx.dto" /> </ bean > <!--创建dao bean(只需提供接口不需提供实现类 )--> < bean id = "userDao" class = "org.mybatis.spring.mapper.MapperFactoryBean" > < property name = "mapperInterface" value = "com.xxx.dao.UserDao" /> < property name = "sqlSessionFactory" ref = "sqlSessionFactory" /> </ bean > |
我们不但要明白如何使用,更要明白为什么要这么使用。
SqlSessionFactoryBean是一个工厂bean,它的作用就是解析配置(数据源、别名等)。
MapperFactoryBean是一个工厂bean,在spring容器里,工厂bean是有特殊用途的,当spring将工厂bean注入到其他bean里时,它不是注入工厂bean本身而是调用bean的getObject方法。我们接下来就看看这个getObjec方法干了些什么:
1
2
3
|
public T getObject() throws Exception { return getSqlSession().getMapper( this .mapperInterface); } |
看到这里大家应该就很明白了,这个方法和我们之前单独使用Mybatis的方式是一样的,都是先获取一个Sqlsession对象,然后再从Sqlsession里获取Mapper对象(再次强调Mapper是一个代理对象,它代理的是mapperInterface接口,而这个接口是用户提供的dao接口)。自然,最终注入到业务层就是这个Mapper对象。
实际的项目一般来说不止一个Dao,如果你有多个Dao那就按照上面的配置依次配置即可。
如何使用批量更新
前一节讲了如何注入一个mapper对象到业务层, mapper的行为依赖于配置,mybatis默认使用单个更新(即ExecutorType默认为SIMPLE而不是BATCH),当然我们可以通过修改mybatis配置文件来修改默认行为,但如果我们只想让某个或某几个mapper使用批量更新就不得行了。这个时候我们就需要使用模板技术:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!--通过模板定制mybatis的行为 --> lt;bean id="sqlSessionTemplateSimple" class="org.mybatis.spring.SqlSessionTemplate"> < constructor-arg index = "0" ref = "sqlSessionFactory" /> <!--更新采用单个模式 --> < constructor-arg index = "1" value = "SIMPLE" /> </ bean > <!--通过模板定制mybatis的行为 --> lt;bean id="sqlSessionTemplateBatch" class="org.mybatis.spring.SqlSessionTemplate"> < constructor-arg index = "0" ref = "sqlSessionFactory" /> <!--更新采用批量模式 --> < constructor-arg index = "1" value = "BATCH" /> </ bean > |
这里笔者定义了两个模板对象,一个使用单个更新,一个使用批量更新。有了模板之后我们就可以改变mapper的行为方式了:
1
2
3
4
|
< bean id = "userDao" class = "org.mybatis.spring.mapper.MapperFactoryBean" > < property name = "mapperInterface" value = "com.xxx.dao.UserDao" /> < property name = "sqlSessionTemplate" ref = " sqlSessionTemplateBatch " /> </ bean > |
跟上一节的mapper配置不同的是,这里不需要配置sqlSessionFactory属性,只需要配置sqlSessionTemplate(sqlSessionFactory属性在模板里已经配置好了)。
通过自动扫描简化mapper的配置
前面的章节可以看到,我们的dao需要一个一个的配置在配置文件中,如果有很多个dao的话配置文件就会非常大,这样管理起来就会比较痛苦。幸好mybatis团队也意识到了这点,他们利用spring提供的自动扫描功能封装了一个自动扫描dao的工具类,这样我们就可以使用这个功能简化配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!-- 采用自动扫描方式创建mapper bean(单个更新模式) --> < bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" > < property name = "basePackage" value = "com.xxx.dao" /> < property name = "sqlSessionTemplateBeanName" value = "sqlSessionTemplateSimple" /> < property name = "markerInterface" value = "com.xxx.dao.SimpleDao" /> </ bean > <!-- 采用自动扫描方式创建mapper bean(批量更新模式) --> < bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" > < property name = "basePackage" value = "com.xxx.dao" /> < property name = "sqlSessionTemplateBeanName" value = "sqlSessionTemplateBatch" /> < property name = "markerInterface" value = "com.xxx.dao.BatchDao" /> </ bean > |
MapperScannerConfigurer本身涉及的spring的技术我就不多讲了,感兴趣且对spring原理比较了解的可以去看下它的源码。我们重点看一下它的三个属性:
-
basePackage:扫描器开始扫描的基础包名,支持嵌套扫描;
-
sqlSessionTemplateBeanName:前文提到的模板bean的名称;
-
markerInterface:基于接口的过滤器,实现了该接口的dao才会被扫描器扫描,与basePackage是与的作用。
除了使用接口过滤外,还可使用注解过滤:
1
2
3
4
5
6
|
<!-- 采用自动扫描方式创建mapper bean(批量更新模式) --> < bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" > < property name = "basePackage" value = "com.xxx.dao" /> < property name = "sqlSessionTemplateBeanName" value = "sqlSessionTemplateBatch" /> < property name = "annotationClass" value = "com.xxx.dao.BatchAnnotation" /> </ bean > |
annotationClass:配置了该注解的dao才会被扫描器扫描,与basePackage是与的作用。
需要注意的是,两个过滤条件只能配一个。
实例:事务管理
定义一个实体类:Emp.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package com.lixing.scm.entity; public class Emp { private String id; private String name; private String sex; private int age; private String phone; public String getId() { return id; } public void setId(String id) { this .id = id; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getSex() { return sex; } public void setSex(String sex) { this .sex = sex; } public int getAge() { return age; } public void setAge( int age) { this .age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this .phone = phone; } } |
定义实体内操作接口:EmpMapper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package com.lixing.scm.test.mapper; import java.util.List; import java.util.Map; import com.lixing.scm.entity.Emp; public interface EmpMapper { void insertEmp(Emp emp); List<Emp> getAllEmp(); Emp getById(String id); void deleteEmp(String id); void updateEmp(Map<String,Object> map); } |
定义实体类操作接口的映射文件:EmpMapper.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> < mapper namespace = "com.lixing.scm.test.mapper.EmpMapper" > < parameterMap type = "com.lixing.scm.entity.Emp" id = "parameterMapEmp" > < parameter property = "id" /> < parameter property = "name" /> < parameter property = "sex" /> < parameter property = "age" /> < parameter property = "phone" /> </ parameterMap > < resultMap type = "com.lixing.scm.entity.Emp" id = "resultMapEmp" > < result property = "id" column = "id" /> < result property = "name" column = "name" /> < result property = "sex" column = "sex" /> < result property = "age" column = "age" /> < result property = "phone" column = "phone" /> </ resultMap > < insert id = "insertEmp" parameterMap = "parameterMapEmp" > INSERT INTO emp(id,name,sex,age,phone) VALUES(?,?,?,?,?) </ insert > < select id = "getAllEmp" resultMap = "resultMapEmp" > SELECT * FROM emp </ select > < select id = "getById" parameterType = "String" resultMap = "resultMapEmp" > SELECT * FROM emp WHERE id=#{value} </ select > < delete id = "deleteEmp" parameterType = "String" > DELETE FROM emp WHERE id=#{value} </ delete > < update id = "updateEmp" parameterType = "java.util.Map" > UPDATE emp SET name=#{name},sex=#{sex},age=#{age},phone=#{phone} WHERE id=#{id} </ update > </ mapper > Spring3.0.6定义: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:context = "http://www.springframework.org/schema/context" xmlns:aop = "http://www.springframework.org/schema/aop" 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/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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- --> < context:annotation-config /> < context:component-scan base-package = "com.lixing.scm.test.*" /> <!-- jdbc.propertis Directory --> < bean class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > < property name = "locations" value = "classpath:jdbc.properties" /> </ bean > < bean id = "MyDataSource" destroy-method = "close" class = "org.apache.commons.dbcp.BasicDataSource" > < property name = "driverClassName" value = "${jdbc.driverClassName}" /> < property name = "url" value = "${jdbc.url}" /> < property name = "username" value = "${jdbc.username}" /> < property name = "password" value = "${jdbc.password}" /> </ bean > <!-- SqlSessionFactory --> < bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" > < property name = "dataSource" ref = "MyDataSource" /> </ bean > <!-- ScanMapperFiles --> < bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" > < property name = "basePackage" value = "com.lixing.scm.test.mapper" /> </ bean > <!-- ================================事务相关控制================================================= --> < bean name = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" > < property name = "dataSource" ref = "MyDataSource" ></ property > </ bean > < tx:advice id = "userTxAdvice" transaction-manager = "transactionManager" > < tx:attributes > < tx:method name = "delete*" propagation = "REQUIRED" read-only = "false" rollback-for = "java.lang.Exception" no-rollback-for = "java.lang.RuntimeException" /> < tx:method name = "insert*" propagation = "REQUIRED" read-only = "false" rollback-for = "java.lang.RuntimeException" /> < tx:method name = "update*" propagation = "REQUIRED" read-only = "false" rollback-for = "java.lang.Exception" /> < tx:method name = "find*" propagation = "SUPPORTS" /> < tx:method name = "get*" propagation = "SUPPORTS" /> < tx:method name = "select*" propagation = "SUPPORTS" /> </ tx:attributes > </ tx:advice > < aop:config > < aop:pointcut id = "pc" expression = "execution(public * com.lixing.scm.test.service.*.*(..))" /> <!--把事务控制在Service层--> < aop:advisor pointcut-ref = "pc" advice-ref = "userTxAdvice" /> </ aop:config > <!-- 以下为自定义Bean--> < bean id = "empDao" class = "com.lixing.scm.test.dao.impl.EmpDaoImpl" autowire = "byName" /> < bean id = "empService" class = "com.lixing.scm.test.service.impl.EmpServiceImpl" autowire = "byName" /> </ beans > |
DAO接口:EmpDAO.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package com.lixing.scm.test.dao; import java.util.List; import java.util.Map; import com.lixing.scm.entity.Emp; public interface EmpDao { void insertEmp(Emp emp); List<Emp> getAllEmp(); Emp getById(String id); void deleteEmp(String id); void updateEmp(Map<String, Object> map); } |
DAO接口实现类:EmpDaoImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
package com.lixing.scm.test.dao.impl; import java.util.List; import java.util.Map; import com.lixing.scm.entity.Emp; import com.lixing.scm.test.dao.EmpDao; import com.lixing.scm.test.mapper.EmpMapper; public class EmpDaoImpl implements EmpDao { private EmpMapper empMapper; //在此处注入一个empMapper //这个empMapper由 Spring自动生成 //不需要我们自己手工去定义 @Override public void insertEmp(Emp emp) { this .empMapper.insertEmp(emp); throw new RuntimeException( "Error" ); //测试抛出RuntimeException //异常查看数据库是否存在记录 } @Override public void deleteEmp(String id) { this .empMapper.deleteEmp(id); } @Override public List<Emp> getAllEmp() { return this .empMapper.getAllEmp(); } @Override public Emp getById(String id) { return this .empMapper.getById(id); } @Override public void updateEmp(Map<String, Object> map) { this .empMapper.updateEmp(map); } public EmpMapper getEmpMapper() { return empMapper; } public void setEmpMapper(EmpMapper empMapper) { this .empMapper = empMapper; } } |
Service层接口:EmpService.java
1
2
3
4
5
6
7
|
package com.lixing.scm.test.service; import com.lixing.scm.entity.Emp; public interface EmpService { void insertEmp(Emp emp); } |
Service层接口实现类:EmpServiceImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package com.lixing.scm.test.service.impl; import com.lixing.scm.entity.Emp; import com.lixing.scm.test.dao.EmpDao; import com.lixing.scm.test.service.EmpService; public class EmpServiceImpl implements EmpService { private EmpDao empDao; @Override public void insertEmp(Emp emp) { empDao.insertEmp(emp); } public EmpDao getEmpDao() { return empDao; } public void setEmpDao(EmpDao empDao) { this .empDao = empDao; } } |
测试类:TestEmpService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.lixing.scm.entity.Emp; import com.lixing.scm.test.service.EmpService; public class TestEmpService { @Test public void testTrasaction(){ Emp emp= new Emp(); emp.setId( "00000003" ); emp.setName( "某某某" ); emp.setAge( 50 ); emp.setSex( "男" ); emp.setPhone( "566666" ); ApplicationContext ctx= new ClassPathXmlApplicationContext( "classpath:applicationContext.xml" ); EmpService service=ctx.getBean(EmpService. class ); service.insertEmp(emp); } } |