SpringBoot-(四)SpringBoot整合MyBatis

本文最后更新于:February 1, 2022 pm

SpringBoot框架中有两个非常重要的策略:开箱即用和约定优于配置。其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

目录

1.导入依赖

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
<?xml version="1.0" encoding="UTF-8"?>
<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tothefor</groupId>
<artifactId>studyandMybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>studyandMybatis</name>
<description>studyandMybatis</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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.2.2</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

</project>

2.配置文件

1
2
3
4
5
6
7
8
9
10
11
# 关闭模板引擎的缓存,防止更改前端代码没有效果
spring:
thymeleaf:
cache: false

datasource:
username: root
password: loong461
url: jdbc:mysql://localhost:3306/link?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.tothefor;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;

@SpringBootTest
class SpringBoot01ApplicationTests {

@Autowired
DataSource dataSource;

@Test
void contextLoads() {
System.out.println(dataSource.getClass());
//class com.zaxxer.hikari.HikariDataSource
}
}

看是否出现报错情况。

3.实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.tothefor.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private int id;
private String name;
}

4.接口

需要使用@Mapper,表示这是一个mybatis的Mapper接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.tothefor.dao;

import com.tothefor.entity.Person;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface PersonMapper {
List<Person> queryall();
}

也可以在主启动类中使用@MapperScan(“com.ththefor.mapper”)进行全局配置扫描

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.tothefor;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.ththefor.dao") //扫描dao目录下的所有接口
public class SpringBoot01Application {
public static void main(String[] args) {
SpringApplication.run(SpringBoot01Application.class, args);
}

}

选择其一即可。

5.mapper文件

在resources目录下建一个mybatis文件夹,在其中再建一个mapper目录,用来存放所有接口的mapper文件。

1
2
3
4
5
6
7
8
9
<?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.tothefor.dao.PersonMapper">
<select id="queryall" resultType="Person">
select * from person
</select>
</mapper>

其中,resultType的值是简写了的,需要添加配置配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 关闭模板引擎的缓存,防止更改前端代码没有效果
spring:
thymeleaf:
cache: false

datasource:
username: root
password: loong461
url: jdbc:mysql://localhost:3306/link?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver

# 整合mybatis
mybatis:
type-aliases-package: com.tothefor.entity # 哪一个包里面的类可以在mapper文件中直接简写为类名
mapper-locations: classpath:mybatis/mapper/*.xml # 找mapper文件的位置,第一个位置不需要斜杠,classpath表示从resources开始

6.使用

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
package com.tothefor.controller;

import com.tothefor.dao.PersonMapper;
import com.tothefor.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController //@ResponseBody和@Controller
public class PersonController {

@Autowired
private PersonMapper personMapper;

@GetMapping("/queryall")
public List<Person> query(){
List<Person> list = personMapper.queryall();
for(Person it: list){
System.out.println(it);
}
return list;
}

}

访问 http://localhost:8080/queryall 即可。

整合Druid

设置整合Druid。

application.yml

1
2
3
spring:
profiles:
active: dev

application-dev.yml

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
# 关闭模板引擎的缓存,防止更改前端代码没有效果
spring:
thymeleaf:
cache: false

datasource:
username: root
password: loong461
url: jdbc:mysql://localhost:3306/link?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource

# Druid连接池 Springboot 默认是不注入这些属性值的,需要自己进行绑定
# 初始化连接数量
initialSize: 10
# 最大连接数量,当初始化的用完时,就继续新建
maxActive: 30
# 最小空闲连接数量,即连初始化的都长时间没有用时,也会将其释放,直至最小空闲连接数量
minIdle: 5
# 超时等待时间,以毫秒为单位。如果有超过最大连接数量的需求,则超过部分需要等待相应的时间,如果超了等待时间,就不会再等,即拿不到连接。
maxWait: 5000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

# 整合mybatis
mybatis:
type-aliases-package: com.tothefor.entity # 哪一个包里面的类可以在mapper文件中直接简写为类名
mapper-locations: classpath:mybatis/mapper/*.xml # 找mapper文件的位置,第一个位置不需要斜杠,classpath表示从resources开始

Druid数据源配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.tothefor.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DuridConfig {

@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
}

测试

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
package com.tothefor;

import com.alibaba.druid.pool.DruidDataSource;
import com.tothefor.dao.PersonMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class StudyandMybatisApplicationTests {

@Autowired
DataSource dataSource;

@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
System.out.println(dataSource);
Connection connection = dataSource.getConnection();
System.out.println(connection);

DruidDataSource ds = (DruidDataSource) dataSource;
System.out.println("druidDataSource 数据源最大连接数:" + ds.getMaxActive());
System.out.println("druidDataSource 数据源初始化连接数:" + ds.getInitialSize());

}

}

总结

步骤

    1. 先写数据库对应的实体类。
    1. 写接口。
    1. 写接口对应的mapper文件。(位置是放在resources目录下的)mapper文件配置后,需要配置文件位置,在application.yml中进行配置。(可参考本例的配置文件)
    1. 其余的正常写业务和控制层。