整合Mybatis
# 510.整合Mybatis
之前我们使用的JdbcTemplate,轻量级的封装;接下来我们整合Mybatis
# 引入starter
Mybatis属于第三方技术,因此SpringBoot官方没有提供starter;为此,Mybatis提供了一个,我们可以访问其GitHub地址 (opens new window),可以进入其spring-boot-starter目录,打开其pom.xml文件,就可以看到当前项目的依赖情况:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot</artifactId>
<version>3.0.3-SNAPSHOT</version>
</parent>
<artifactId>mybatis-spring-boot-starter</artifactId>
<name>mybatis-spring-boot-starter</name>
<properties>
<module.name>org.mybatis.spring.boot.starter</module.name>
</properties>
...........
2
3
4
5
6
7
8
9
10
11
12
13
我们只需引入其定义的依赖即可:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
2
3
4
5
# 自动配置分析
在之前我们使用Mybatis,都是定义一个全局配置文件,SqlSessionFactory,SqlSession和Mapper,我们看看Mybatis是否配置好了。
starter引入了如下依赖:一个是JDBC的,一个是自动配置的,还引入了Mybatis,Mybatis和Spring的整合
我们来看看其自动配置了什么。首先我们看spring.factories:
之前我们说过,SpringBoot启动的时候会自动加载这个文件,然后开启自动配置:
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
2
3
4
我们来看看MybatisAutoConfiguration
:
@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
public class MybatisAutoConfiguration implements InitializingBean {
//.....
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
//.....
}
@Bean
@ConditionalOnMissingBean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
//.....
}
@org.springframework.context.annotation.Configuration
@Import(AutoConfiguredMapperScannerRegistrar.class)
@ConditionalOnMissingBean({ MapperFactoryBean.class, MapperScannerConfigurer.class })
public static class MapperScannerRegistrarNotFoundConfiguration
//.....
}
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
先来说说类上的注解:
@ConditionalOnClass
:只有引入了Mybatis的依赖,该配置才生效@ConditionalOnSingleCandidate(DataSource.class)
:有且只有一个数据源的时候,才会生效;@EnableConfigurationProperties
:绑定Mybatis配置,因此如果要配置Mybatis,配置项的前缀就是mybatis。
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {
public static final String MYBATIS_PREFIX = "mybatis";
//...........
2
3
4
5
再看看该自动配置类,注入的bean:
SqlSessionFactory
,并且配置了数据源SqlSessionTemplate
则相当于是SqlSession
,用来操作数据库的。MapperScannerRegistrarNotFoundConfiguration
:相当于是Mapper的扫描配置,会自动扫描用了@Mapper注解的类,我们可以看看其Import的类:
public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
logger.debug("Searching for mappers annotated with @Mapper");
List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
if (logger.isDebugEnabled()) {
packages.forEach(pkg -> logger.debug("Using auto-configuration base package '{}'", pkg));
}
//..........
2
3
4
5
6
7
8
9
10
11
12
# 开始使用Mybatis
我们使用Mybatis,来写一个案例,忘了的同学可以复习下:Mybatis | 从01开始 (opens new window)
新建一个实体类:
package com.peterjxl.learnspringbootwebadmin.bean;
import lombok.Data;
@Data
public class Student {
private Integer id;
private String name;
private int gender;
private int grade;
private int score;
}
2
3
4
5
6
7
8
9
10
11
12
新增一个代理接口:
package com.peterjxl.learnspringbootwebadmin.mapper;
import com.peterjxl.learnspringbootwebadmin.bean.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentMapper {
Student selectStudentById(Integer id);
}
2
3
4
5
6
7
8
9
10
11
新增service层:
package com.peterjxl.learnspringbootwebadmin.service;
import com.peterjxl.learnspringbootwebadmin.bean.Student;
import com.peterjxl.learnspringbootwebadmin.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
@Autowired
private StudentMapper studentMapper;
public Student selectStudentById(Integer id) {
return studentMapper.selectStudentById(id);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
新增表现层
我们找一个controller,调用service层的方法:
@Controller
public class IndexController {
@Autowired
StudentService studentService;
@GetMapping("/stu")
public Student getStudentById(@RequestParam("id") Integer id) {
return studentService.selectStudentById(id);
}
//.............
2
3
4
5
6
7
8
9
10
11
新建全局的配置文件:resources/mybatis/mybatis-config.xml
<?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="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
2
3
4
5
6
7
8
9
为了方便,我们开启了驼峰式命名的配置。例如数据库中,列的名字是user_id,那么在Java类中只需定义userId,也可绑定值。
ps:也可在yml文件中配置该项,但是这样的话,在yml中就不能指定全局配置文件了,因为用了两种配置方式的话(全局配置文件+yml文件),Mybatis就不知道以哪个为准
新增Mapper配置文件:
<?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.peterjxl.learnspringbootwebadmin.mapper.StudentMapper">
<select id="selectStudentById" resultType="com.peterjxl.learnspringbootwebadmin.bean.Student">
select * from students where id = #{id}
</select>
</mapper>
2
3
4
5
6
7
8
9
10
11
修改application.yml文件,增加Mybatis的配置,指定全局配置文件和Mapper文件的位置:
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
2
3
重启,访问路径,可以看到能正常查询出来数据:
# 总结
使用步骤:
- 导入starter
- 编写mapper接口(要标注@Mapper接口)
- 编写mapper映射文件,绑定mapper接口
- 在application.yml中指定配置文件的信息(建议不使用全局配置文件)
其实也可以在初始化SpringBoot项目的时候,选择Mybatis的依赖,这样能省略一些步骤:
已将本文源码上传到Gitee (opens new window)或GitHub (opens new window) 的分支demo12,读者可以通过切换分支来查看本文的示例代码