本系列文章:
Mybatis(一)Mybatis的基本使用
Mybatis(二)Mybatis的高级使用
Mybatis(三)集成Mybatis
一、Spring集成MyBatis
现在的项目多用SpringBoot框架开发,因为开发起来方便快捷。此处,可了解下在比较原始的Spring项目中,怎么集成Mybatis。
以一个Maven形式的Spring(也可以说是SpringMVC项目,因为代码已按MVC分层)项目为例:
src/main/java目录下的业务代码,分为Controller、Service、DAO、实体类4个目录。
src/test目录下为单测代码。
src/main/resurces目录下为XxxMapper.xml和各种配置文件,applicationContext.xml是Spring项目的总体配置文件,log4j.proterties为日志框架的配置文件,其他两个为Mybatis的配置文件。
src/main/webapp目录下是前端文件和web.xml,web.xml里是一些监听器、过滤器等的配置。
现在假设已经有了一个正常的Spring MVC项目,接下来就集成Mybatis框架。
- 1、在pom.xml中添加mybatis-spring依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
- 2、配置SqlSessionFactoryBean
在MyBatis–Spring中,SqlSessionFactoryBean是用于创建SqlSessionFactory的。在Spring配置文件applicationContext.xml中配置这个工厂类,代码示例:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations">
<array>
<value>classpath:tk/mybatis/**/mapper/*.xml</value>
</array>
</property>
<property name="typeAliasesPackage" value="tk.mybatis.web.model"/>
</bean>
在配置SqlSessionFactoryBean时,用到了最常用的几个属性配置。
configLocation
:用于配置mybatis配置XML的路径,除了数据源外,对MyBatis的各种配置仍然可以通过这种方式进行。
面配置的mybatis-config.xml位于src/main/resources目录下,配置文件内容示例:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="LOG4J"/>
<setting name="cacheEnabled" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
</configuration>
dataSource
:用于配置数据源,该属性为必选项,必须通过这个属性配置数据源。
mapperLocations
:配置SqlSessionFactoryBean扫描XML映射文件的路径,可以使用Ant风格的路径进行配置。
typeAliasesPackage
:配置包中类的别名,配置后,包中的类在XML映射文件中使用时可以省略包名部分,直接使用类名。这个配置不支持At风格的路径,当需要配置多个包路径时可以使用分号或逗号进行分隔。
- 3、配置MapperScannerConfigurer
在之前和Spring集成的例子中,可能会有许多直接使用SqlSession的代码,或者使用了Mapper接口但是需要自己实现接口的用法。这些用法在iBATIS时期或者比较老的MyBatis项目中存在。这里要介绍的用法是最简单且推荐使用的一种,通过MapperScannerConfigurer类自动扫描所有的Mapper接口,使用时可以直接注入接口。
在Spring配置文件applicationContext.xml中配置扫描类,代码示例:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage"value="tk.mybatis.**.mapper"/>
</bean>
MapperScannerConfigurer中常配置以下两个属性。
basePackage
:用于配置基本的包路径。可以使用分号或逗号作为分隔符设置多于一个的包路径,每个映射器将会在指定的包路径中递归地被搜索到。
annotationclass
:用于过滤被扫描的接口,如果设置了该属性,那么MyBatis的接口只有包含该注解才会被扫描进去。
- 4、在业务代码中使用Mybatis
先做一些准备工作,比如一些表、数据、实体类等。
-- 字典表
DROP TABLE IF EXISTS `sys_dict`;
CREATE TABLE `sys_dict` (
`id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '主键',
`code` varchar(64) NOT NULL COMMENT '类别',
`name` varchar(64) NOT NULL COMMENT '字典名',
`value` varchar(64) NOT NULL COMMENT '字典值',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
INSERT INTO `sys_dict` VALUES ('1', '性别', '男', '男');
INSERT INTO `sys_dict` VALUES ('2', '性别', '女', '女');
INSERT INTO `sys_dict` VALUES ('3', '季度', '第一季度', '1');
INSERT INTO `sys_dict` VALUES ('4', '季度', '第二季度', '2');
INSERT INTO `sys_dict` VALUES ('5', '季度', '第三季度', '3');
INSERT INTO `sys_dict` VALUES ('6', '季度', '第四季度', '4');
在src/main/java中新建tk.mybatis.web.model包,然后新建SysDict实体类。
public class SysDict implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String code;
private String name;
private String value;
//gettter和setter
}
接下来开发DAO层。新建tk.mybatis…web.mapper包,然后新建DictMapper接口,定义一个查询方法。
public interface DictMapper{
/**
* 根据主键查询
*
* @param id
* @return
*/
SysDict selectByPrimaryKey(Long id);
}
在src/main/resources中新建tk/mybatis//web/mapper/目录,然后新建DictMapper.xml文件,写入上面的查询方法selectByPrimaryKey对应的SQL实现。
<?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="tk.mybatis.web.mapper.DictMapper">
<select id="selectByPrimaryKey"resultType="SysDict">
select id,code,name,value from sys_dict where id =#(id}'
</select>
</mapper>
然后在业务代码里就可以使用这个查询接口了。示例:
@Autowired
private DictMapper dictMapper;
@Override
public SysDict findById(Long id) {
return dictMapper.selectByPrimaryKey(id);
}
二、SpringBoot集成MyBatis
SpringBoot是目前Web项目的主流开发方式,因为其使用比较简单方便。SpringBoot项目结构示例:
这是前后端分离的SpringBoot项目,因此没有前端相关的代码。假设已经有了一个基础的SpringBoot项目,接下来集成Mybatis。
- 1、在pom.xml中引入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
- 2、添加DAO层接口
然后在tk.mybatis…springboot.mapper包下新建CountryMapper接口。
@Mapper
public interface CountryMapper {
/**
* 查询全部数据
*
* @return
*/
List<Country> selectAll();
}
这里使用了@Mapper注解,增加这个注解之后,Spring启动时会自动扫描该接口,这样就可以在需要使用时直接注入Mapper了。
在src/main/resources下面创建mapper目录,然后新建CountryMapper.xml映射文件。
<?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="tk.mybatis.springboot.mapper.CountryMapper">
<select id="selectAll" resultType="Country">
select id,countryname,countrycode from country
</select>
</mapper>
- 3、配置Mybatis
在application.properties配置文件中添加如下内容。
#映射文件的路径,支持At风格的通配符,多个配置可以使用英文逗号隔开
mybatis.mapperLocations=classpath:mapper/*.xml
#类型别名包配置,只能指定具体的包,多个配置可以使用英文逗号隔开
mybatis.typeAliasesPackage=tk.mybatis.springboot.model
- 4、在业务代码中使用该接口
@Autowired
private CountryMapper countryMapper;
List<Country> countries = countryMapper.selectAll();