今天主要介绍一下SpringBoot与MyBatis框架的整合,主要介绍两种方式的整合,一种是我们传统的xml配置文件的方式,另外一种是我们springBoot推崇的配置文件的方式整合。
配置文件方式
首先来介绍一下基于配置文件的整合;
首先需要我们创建一个SpringBoot的Maven项目,这里使用的是IDEA工具,选择需要的模块,Maven会默认的下载好;无需我们再去关心引入;主要看mybatis包有没有引入。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
接下来我们配置我们的数据源,在配置文件中写入数据库配置;这里使用的是.yml文件的配置;
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3308/SPRINGBOOT
driver-class-name: com.mysql.jdbc.Driver
# 阿里的DruidDataSource数据源可以看到后台监控
# type: type: com.alibaba.druid.pool.DruidDataSource
# springframework.jdbc提供的数据源
type: org.springframework.jdbc.datasource.DriverManagerDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
接下来我们写我们的Mybatis的全局配置文件mybatis-config.xml;可以参考官网的配置文件,需要什么配置什么;
Mybatis中文官网配置文件链接
<?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"/>
<!--设置主键自增-->
<setting name="useGeneratedKeys" value="true"/>
</settings>
</configuration>
接着我们创建mybatis映射文件**mapper.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.eml.mapper.CustMapper">
<select id="findCustById" resultType="com.eml.domain.Cust">
select * from CUST where id = #{id}
</select>
</mapper>
配置文件写完后可以开始写代码;首先是domain实体类,这里简单的创建没有太多字段;后面我会把代码传上去,以及sql文件,需要的可以下载简单的看一下;
domain
public class Cust {
private Integer id;
private String custName;
private Integer custAge;
private String custGender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public Integer getCustAge() {
return custAge;
}
public void setCustAge(Integer custAge) {
this.custAge = custAge;
}
public String getCustGender() {
return custGender;
}
public void setCustGender(String custGender) {
this.custGender = custGender;
}
@Override
public String toString() {
return "Cust{" +
"id=" + id +
", custName='" + custName + '\'' +
", custAge=" + custAge +
", custGender='" + custGender + '\'' +
'}';
}
}
custMapper (interface)
public interface CustMapper {
Cust findCustById(Integer id);
int insertCust(Cust cust);
}
custMapper(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.eml.mapper.CustMapper">
<select id="findCustById" resultType="com.eml.domain.Cust">
select * from CUST where id = #{id}
</select>
<insert id="insertCust">
insert into CUST(CUST_NAME,CUST_AGE,CUST_GENDER) VALUES (#{custName},#{custAge},#{custGender})
</insert>
</mapper>
controler
@Controller
public class CustController {
@Autowired
CustMapper custMapper;
@ResponseBody
@GetMapping("/findCustById/{id}")
public Cust custfinById(@PathVariable("id") int id){
Cust cust = custMapper.findCustById(id);
return cust;
}
@ResponseBody
@GetMapping("/insertCust")
public int insertCust(Cust cust){
int total = custMapper.insertCust(cust);
return total;
}
}
项目结构
代码完成后,在配置文件中最后需要添加mybatis全局配置文件,以及mapper映射文件;
mybatis:
# 配置文件位置
config-location: classpath:mybatis-config.xml
# sql映射文件位置
mapper-locations: classpath:mapper/*.xml
接下来就是启动测试:
查询,先前数据表中有的数据
新增:
新增成功后返回,插入条数;到这里我们就可以通过springboot整合我们之前的配置文件形式,已经成功使用,下面我们说一下通过配置文件的形式更便捷的开发形式;
首先我们可以看一下mybatis的自动配置类,看自动配置为我们已经配置了哪些东西,我们在配置文件中写的时候该如何使用;
全局搜索 MybatisAutoConfiguration 配置文件,
@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)//properties
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {
配置文件的@EnableConfigurationProperties注解,查看能配置哪些内容;
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {
public static final String MYBATIS_PREFIX = "mybatis";
/**
* Location of MyBatis xml config file.
*/
private String configLocation;
我这里都是截取,具体可以自己去看和配置。基本的我们不配置也能使用;
domain文件
public class User {
private Integer id;
private String userName;
private String userAge;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", userAge='" + userAge + '\'' +
'}';
}
mapper(interface)
@Mapper
public interface UserMapper {
@Select("select * from USER where id=#{id}")
User getUserById(int id);
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert("insert into USER (USER_NAME,USER_AGE) VALUES (#{userName},#{userAge})")
int insertUser(User user);
}
controller
public class CustController {
@Autowired
CustMapper custMapper;
@ResponseBody
@GetMapping("/findCustById/{id}")
public Cust custfinById(@PathVariable("id") int id){
Cust cust = custMapper.findCustById(id);
return cust;
}
@ResponseBody
@GetMapping("/insertCust")
public int insertCust(Cust cust){
int total = custMapper.insertCust(cust);
return total;
}
}
测试:
新增操作;
查询;查询刚才插入的数据
这里需要还需要说明的有两点;一个是全局的Mapper文件扫描到容器中,可以在启动类直接扫描全部,就无需再在每一个mapper文件中加@Mapper注解;
我们可以看一下自动配置扫描mapper是怎么做的;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
logger.debug("Searching for mappers annotated with @Mapper");
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
try {
if (this.resourceLoader != null) {
scanner.setResourceLoader(this.resourceLoader);
}
List<String> packages = AutoConfigurationPackages.get(this.beanFactory);
if (logger.isDebugEnabled()) {
for (String pkg : packages) {
logger.debug("Using auto-configuration base package '{}'", pkg);
}
}
scanner.setAnnotationClass(Mapper.class);
scanner.registerFilters();
scanner.doScan(StringUtils.toStringArray(packages));
} catch (IllegalStateException ex) {
logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.", ex);
}
}
我们也可以自己配置;
第二点就是我们的自定义我们的配置文件;
我们可以new 一个新的 ConfigurationCustomizer 对象加入容器的方式来自定义我们自己的配置;例如我们像xml文件配置一样启动驼峰命令转换;
@org.springframework.context.annotation.Configuration
public class MybatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);//启动驼峰命名
}
};
}
}
通过自定义配置的方式;将配置信息作用到容器中;
上面就是两种实现mybatis整合的方式。项目中还整合了Druid数据源,可以监控我们的监控后太的sql数据查询等;使用的时候只需将配置文件中的datasource 的type属性切换过来即可;
这里就不一一介绍;
可以查看源码实现,github地址