1. 简介
在SSM项目中整合MyBatis时,需要开发者自己提供两个Bean:SqlSessionFactoryBean和MapperScannerConfigurer。在Spring Boot中当我们添加了MyBatis的依赖后即为我们自动配置了这两个Bean了。不需要开发者自行提供,使MyBatis基本上做到开箱即用。
下面来看看如果Spring Boot中如何整合MyBatis以及简单测试
2. 依赖添加
在创建好的Spring Boot项目中pom.xml中添加如下依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>5.1.29</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
3. 数据库配置
在application.properties中提供以下基本配置:
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=123456
配置完成后,就可以通过创建Mapper来使用MyBatis了。
4. 简单测试
数据准备
我这里是在数据库springboot下创建student表,sql脚本如下:
create table student(
id int auto_increment PRIMARY KEY,
name VARCHAR(30)
);
insert into student(id,name) values(1,'张3');
insert into student(id,name) values(2,'张4');
insert into student(id,name) values(3,'张5');
insert into student(id,name) values(4,'张6');
创建Bean
这里我创建一个bean包,里面创建一个Student,属性名对应数据库字段名
public class Student {
private int id;
private String name;
//getter和setter方法省略
}
创建Mapper
这里我创建一个mapper包,里面创建一个StudentMapper接口
public interface StudentMapper {
public List<Student> queryAllStu();
}
Mapper映射
mapper对应的xml可以放置的位置有两个,第一个直接放在mapper包下,放在这里的xml会被自动扫描到,但是有另外一个Maven带来的问题,就是java目录下的xml文件在项目打包时会被忽略掉。
所以,如果xml放在mapper包下,需要在pom.xml文件中再添加如下配置,避免打包时java目录下的XML文件被自动忽略掉:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
第二个位置就是直接放在resources目录下,这样就不用担心打包时被忽略了,但是放在resources目录下,不会自动被扫描到,需要添加额外配置。
例如我在resources目录下创建mapper目录用来放StudentMapper文件,如下:
然后在application.properties中配置mapper的位置
mybatis.mapper-locations=classpath:mapper/*.xml
这样就可以使用mapper了。
我这里使用第一种方式,直接将xml文件放在mapper包下,方便后续多数据源的配置。
StudentMapper.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="com.learn.mybatis.mapper.StudentMapper">
<select id="queryAllStu" resultType="com.learn.mybatis.bean.Student">
select * from student
</select>
</mapper>
测试
首先配置mapper扫描,在启动类或测试类中加上注解@MapperScan并指定包。另一种方式是直接在mapper接口上加@mapper注解,这种方式需要一个个配。
接下来在项目的测试类进行简单测试:
@SpringBootTest
@MapperScan(basePackages = "com.learn.mybatis.mapper")
class MybatisApplicationTests {
@Autowired
StudentMapper studentMapper;
@Test
void contextLoads() {
List<Student> list=studentMapper.queryAllStu();
for (Student student:list){
System.out.println("编号:"+student.getId()+ "姓名:"+student.getName());
}
}
}
测试结果:
5. 多数据源配置
5.1 依赖引入
以上面的项目为基础,在pom.xml中添加Druid依赖。注意添加的是专门为Spring Boot添加的druid-spring-boot-starter。
<!-- druid数据库连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
修改配置文件,指定数据库连接池为druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=123456
5.2 数据准备
我这里在另一个数据库ssm中创建Teacher表,sql脚本如下:
create table teacher(
id int auto_increment PRIMARY KEY,
name VARCHAR(30)
);
insert into teacher(id,name) values(1,'老师1');
insert into teacher(id,name) values(2,'老师2');
insert into teacher(id,name) values(3,'老师3');
insert into teacher(id,name) values(4,'老师4');
创建对应的实体类Teacher
public class Teacher {
private int id;
private String name;
}
//getter和setter方法省略
5.3 数据源配置
在application.properties中配置数据源,这里以两个数据源为例:
#数据源1
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.one.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.one.username=root
spring.datasource.one.password=123456
#数据源2
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.two.url=jdbc:mysql://localhost:3306/ssm
spring.datasource.two.username=root
spring.datasource.two.password=123456
加了one和two区分不同数据源后,这里的配置就不能被Spring Boot自动加载,这就需要我们在新建一个配置类来加载这两个数据源。
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.one")
DataSource dsOne(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.two")
DataSource dsTwo(){
return DruidDataSourceBuilder.create().build();
}
}
这里提供了两个Bean,其中@ConfigurationProperties是Spring Boot提供的类型安全的属性绑定,以第一个Bean为例,@ConfigurationProperties(prefix = “spring.datasource.one”)表示使用spring.datasource.one前缀的数据库配置去创建一个DataSource。通过以上配置,我们就有了两个不同的DataSource。
5.4 MyBatis配置
第一个数据源的配置,对应springboot数据库
@Configuration
@MapperScan(basePackages = "com.learn.mybatis.mapper",sqlSessionFactoryRef ="sqlSessionFactory1" ,sqlSessionTemplateRef ="sqlSessionTemplate1" )
public class MyBatisConfigOne {
@Resource(name = "dsOne")
DataSource dsOne;
@Bean
SqlSessionFactory sqlSessionFactory1() {
SqlSessionFactory sessionFactory = null;
try {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dsOne);
sessionFactory = bean.getObject();
} catch (Exception e) {
e.printStackTrace();
}
return sessionFactory;
}
@Bean
SqlSessionTemplate sqlSessionTemplate1() {
return new SqlSessionTemplate(sqlSessionFactory1());
}
}
首先通过@Configuration指明该类是一个配置类,MapperScan指明要扫描的包是com.learn.mybatis.mapper,即该包下的Mapper接口将操作dsOne中的数据,对应的SqlSessionFactory和SqlSessionTemplate分别是sqlSessionFactory1和sqlSessionTemplate1,SqlSessionFactory1根据dsOne创建,然后再根据创建好的SqlSessionFactory1创建一个SqlSessionTemplate1。
第二个数据源的配置,对应ssm数据库,与前一个配置类似:
@Configuration
@MapperScan(basePackages = "com.learn.mybatis.mapper2",sqlSessionFactoryRef ="sqlSessionFactory2" ,sqlSessionTemplateRef ="sqlSessionTemplate2" )
public class MyBatisConfigTwo {
@Resource(name = "dsTwo")
DataSource dsTwo;
@Bean
SqlSessionFactory sqlSessionFactory2() {
SqlSessionFactory sessionFactory = null;
try {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dsTwo);
sessionFactory = bean.getObject();
} catch (Exception e) {
e.printStackTrace();
}
return sessionFactory;
}
@Bean
SqlSessionTemplate sqlSessionTemplate2() {
return new SqlSessionTemplate(sqlSessionFactory2());
}
}
5.5 测试
创建com.learn.mybatis.mapper2包,在该包下创建TeacherMapper接口
public interface TeacherMapper {
public List<Teacher> queryAllTea();
}
在该包下创建对应的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="com.learn.mybatis.mapper2.TeacherMapper">
<select id="queryAllTea" resultType="com.learn.mybatis.bean.Teacher">
select * from teacher
</select>
</mapper>
包目录结构如下:
这里在测试类中进行简单测试,因为前面配置类中已经配置了注解@MapperScan扫描了Mapper,所以这里不需要额外添加@MapperScan了。
@SpringBootTest
class MybatisApplicationTests {
@Autowired
StudentMapper studentMapper;
@Autowired
TeacherMapper teacherMapper;
@Test
void contextLoads() {
List<Student> list=studentMapper.queryAllStu();
for (Student student:list){
System.out.println("编号:"+student.getId()+ "姓名:"+student.getName());
}
List<Teacher> teacherList=teacherMapper.queryAllTea();
for (Teacher teacher:teacherList){
System.out.println("编号:"+teacher.getId()+ "姓名:"+teacher.getName());
}
}
}
测试结果: