28.整合mybatis

 

1.使用注解方式

项目工程结构:

(1) MyDirectory.java

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
package com.example.demo.entity;

public class MyDirectory {
private Integer directoryId;

private String directoryName;

private String remark;

private Integer userId;

public MyDirectory() {
super();
}

public MyDirectory(Integer directoryId, String directoryName, String remark, Integer userId) {
super();
this.directoryId = directoryId;
this.directoryName = directoryName;
this.remark = remark;
this.userId = userId;
}

public Integer getDirectoryId() {
return directoryId;
}

public void setDirectoryId(Integer directoryId) {
this.directoryId = directoryId;
}

public String getDirectoryName() {
return directoryName;
}

public void setDirectoryName(String directoryName) {
this.directoryName = directoryName == null ? null : directoryName.trim();
}

public String getRemark() {
return remark;
}

public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

@Override
public String toString() {
return "MyDirectory [directoryId=" + directoryId + ", directoryName=" + directoryName + ", remark=" + remark
+ ", userId=" + userId + "]";
}

}

(2) MyDirectoryMapper.java

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
package com.example.demo.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
//import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.example.demo.entity.MyDirectory;

/*
* 想要让SpringBoot识别到这个Mapper接口类
* 方法一: 在mapper.java上添加@Mapper注解
* 方法二: 在启动类上添加@MapperScan(basePackages = {"com.example.demo.dao"})
*/
//@Mapper
public interface MyDirectoryMapper {

@Delete("delete from t_directory where directory_id = #{directoryId}")
int deleteByPrimaryKey(Integer directoryId);

@Insert("insert into t_directory(directory_name, remark, user_id) values(#{directoryName}, #{remark}, #{userId})")
int insert(MyDirectory record);

@Select("select directory_id as directoryId, directory_name as directoryName, remark, user_id as userId from t_directory where directory_id = #{directoryId}")
MyDirectory selectByPrimaryKey(Integer directoryId);

@Update("update t_directory set directory_name = #{directoryName}, remark = #{remark}, user_id = #{userId} where directory_id = #{directoryId}")
int updateByPrimaryKey(MyDirectory record);

@Select("select * from t_directory")
public List<MyDirectory> getAllDirectory();

}

(3) 启动类:

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

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

/*
* 想要让SpringBoot识别到这个Mapper接口类
* 方法一: 在mapper.java上添加@Mapper注解
* 方法二: 在启动类上添加@MapperScan(basePackages = {"com.example.demo.dao"})
*/
@SpringBootApplication
@MapperScan(basePackages = {"com.example.demo.dao"})
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

(4) mybatis.cfg.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?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>
<!-- 让log4j去记录sql日志,打印mybatis执行的sql语句 -->
<setting name="logImpl" value="LOG4J"/>
</settings>

</configuration>

(5) application.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
# 数据源配置信息
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo_filesystem
username: root
password: 123456
initial-size: 3
min-idle: 2
max-active: 10
max-wait: 15000

stat-view-servlet:
login-username: admin
login-password: 123456
# allow和deny可以为空
allow: 192.168.10.25,127.0.0.1,192.168.30.23,192.168.5.26
deny:
url-pattern: /druid/*
# 默认为false,不开启
enabled: true

# mybatis
mybatis:
config-location: classpath:mybatis.cfg.xml

(6) log4j.properties

1
2
3
4
5
6
7
8
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

(7) 测试类:

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

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

import com.example.demo.dao.MyDirectoryMapper;
import com.example.demo.entity.MyDirectory;

@SpringBootTest
class ApplicationTests {

@Autowired
private MyDirectoryMapper myDirectoryMapper;

@Test
void contextLoads() {
MyDirectory myDirectory = myDirectoryMapper.selectByPrimaryKey(1);
System.out.println(myDirectory);
// MyDirectory [directoryId=1, directoryName=home, remark=home目录, userId=1]
}

}

(8) pom.xml

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
<?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.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>15_springboot_mybatis-1</artifactId>
<version>1.0</version>
<name>15_springboot_mybatis-1</name>
<description>Spring Boot mybatis-1</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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- druid-spring-boot-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.9</version>
</dependency>

<!-- mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>

<!-- spring-boot-starter-log4j -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

2.使用Mapper.xml

(1) MyDirectoryMapper.java

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

import java.util.List;

//import org.apache.ibatis.annotations.Mapper;

import com.example.demo.entity.MyDirectory;

//@Mapper
public interface MyDirectoryMapper {

int deleteByPrimaryKey(Integer directoryId);

int insert(MyDirectory record);

MyDirectory selectByPrimaryKey(Integer directoryId);

int updateByPrimaryKey(MyDirectory record);

public List<MyDirectory> getAllDirectory();

}

(2) MyDirectoryMapper.xml

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
80
81
82
83
84
85
86
87
88
89
90
<?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.example.demo.dao.MyDirectoryMapper" >
<resultMap id="BaseResultMap" type="com.example.demo.entity.MyDirectory" >
<id column="directory_id" property="directoryId" jdbcType="INTEGER" />
<result column="directory_name" property="directoryName" jdbcType="VARCHAR" />
<result column="remark" property="remark" jdbcType="VARCHAR" />
<result column="user_id" property="userId" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
directory_id, directory_name, remark, user_id
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from t_directory
where directory_id = #{directoryId,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_directory
where directory_id = #{directoryId,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.example.demo.entity.MyDirectory" >
insert into t_directory (directory_id, directory_name, remark,
user_id)
values (#{directoryId,jdbcType=INTEGER}, #{directoryName,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR},
#{userId,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.example.demo.entity.MyDirectory" >
insert into t_directory
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="directoryId != null" >
directory_id,
</if>
<if test="directoryName != null" >
directory_name,
</if>
<if test="remark != null" >
remark,
</if>
<if test="userId != null" >
user_id,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="directoryId != null" >
#{directoryId,jdbcType=INTEGER},
</if>
<if test="directoryName != null" >
#{directoryName,jdbcType=VARCHAR},
</if>
<if test="remark != null" >
#{remark,jdbcType=VARCHAR},
</if>
<if test="userId != null" >
#{userId,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.example.demo.entity.MyDirectory" >
update t_directory
<set >
<if test="directoryName != null" >
directory_name = #{directoryName,jdbcType=VARCHAR},
</if>
<if test="remark != null" >
remark = #{remark,jdbcType=VARCHAR},
</if>
<if test="userId != null" >
user_id = #{userId,jdbcType=INTEGER},
</if>
</set>
where directory_id = #{directoryId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.example.demo.entity.MyDirectory" >
update t_directory
set directory_name = #{directoryName,jdbcType=VARCHAR},
remark = #{remark,jdbcType=VARCHAR},
user_id = #{userId,jdbcType=INTEGER}
where directory_id = #{directoryId,jdbcType=INTEGER}
</update>

<!-- 查询所有文件夹 -->
<select id="getAllDirectory" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_directory
</select>

</mapper>

(3) application.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
# 数据源配置信息
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo_filesystem
username: root
password: 123456
initial-size: 3
min-idle: 2
max-active: 10
max-wait: 15000

stat-view-servlet:
login-username: admin
login-password: 123456
# allow和deny可以为空
allow: 192.168.10.25,127.0.0.1,192.168.30.23,192.168.5.26
deny:
url-pattern: /druid/*
# 默认为false,不开启
enabled: true

# mybatis
mybatis:
config-location: classpath:mybatis.cfg.xml
# 添加mapper.xml
# 方法一:在application.yml中设置mybatis.mapper-locations
# 方法二:在mybatis.cfg.xml中配置<mappers>
mapper-locations:
- classpath:mapper/*Mapper.xml

(4) mybatis.cfg.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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>
<!-- 让log4j去记录sql日志,打印mybatis执行的sql语句 -->
<setting name="logImpl" value="LOG4J"/>
</settings>

<!--
添加mapper.xml
方法一:在application.yml中设置mybatis.mapper-locations
方法二:在mybatis.cfg.xml中配置<mappers>
-->
<!--
<mappers>
<mapper resource="mapper/MyDirectoryMapper.xml"/>
</mappers>
-->
</configuration>

(5) 测试类

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

import java.util.Iterator;
import java.util.List;

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

import com.example.demo.dao.MyDirectoryMapper;
import com.example.demo.entity.MyDirectory;

@SpringBootTest
class ApplicationTests {

@Autowired
private MyDirectoryMapper myDirectoryMapper;

@Test
public void testQueryAllDirectory() {
List<MyDirectory> directoryList = myDirectoryMapper.getAllDirectory();
for (MyDirectory myDirectory : directoryList) {
System.out.println(myDirectory);
/*
2022-06-18 09:12:25.375 INFO 14184 --- [ main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
2022-06-18 09:12:26.311 INFO 14184 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
2022-06-18 09:12:26.744 INFO 14184 --- [ main] com.example.demo.ApplicationTests : Started ApplicationTests in 2.136 seconds (JVM running for 2.916)
DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5f2de715] was not registered for synchronization because synchronization is not active
DEBUG [main] - JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2f3166a] will not be managed by Spring
DEBUG [main] - ==> Preparing: select directory_id, directory_name, remark, user_id from t_directory
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 16
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5f2de715]
MyDirectory [directoryId=1, directoryName=home, remark=home目录, userId=1]
MyDirectory [directoryId=2, directoryName=usr, remark=usr目录, userId=1]
MyDirectory [directoryId=3, directoryName=source, remark=source目录, userId=1]
MyDirectory [directoryId=4, directoryName=tmp, remark=tmp目录, userId=2]
MyDirectory [directoryId=5, directoryName=bin, remark=bin目录, userId=1]
MyDirectory [directoryId=6, directoryName=boot, remark=boot目录, userId=2]
MyDirectory [directoryId=7, directoryName=dev, remark=dev目录, userId=1]
MyDirectory [directoryId=8, directoryName=etc, remark=etc目录, userId=1]
MyDirectory [directoryId=9, directoryName=var, remark=var目录, userId=1]
MyDirectory [directoryId=10, directoryName=test1, remark=test11, userId=1]
MyDirectory [directoryId=11, directoryName=test2, remark=test22, userId=1]
MyDirectory [directoryId=15, directoryName=css, remark=css file, userId=1]
MyDirectory [directoryId=16, directoryName=js, remark=js file, userId=1]
MyDirectory [directoryId=17, directoryName=jar, remark=jar包目录1, userId=1]
MyDirectory [directoryId=18, directoryName=doc, remark=word文档,doc和docx, userId=1]
MyDirectory [directoryId=19, directoryName=xls, remark=xls表格,xls和xlsx, userId=1]
2022-06-18 09:12:27.063 INFO 14184 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ...
2022-06-18 09:12:27.066 INFO 14184 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed
*/
}
}

}

3.不使用mybatis.cfg.xml

直接去除mybatis.cfg.xml,项目也可以正常运行,得到查询结果,但是没有sql语句的打印输出,以下配置为添加sql语句打印输出

(1) 删除mybatis.cfg.xml

(2) 修改application.yml

1
2
3
4
5
6
7
8
9
# spring.datasource ...
# mybatis
mybatis:
# 删除config-location: classpath:mybatis.cfg.xml
mapper-locations:
- classpath:mapper/*Mapper.xml
# 配置输出日志
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

(3) 测试类

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

import java.util.List;

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

import com.example.demo.dao.MyDirectoryMapper;
import com.example.demo.entity.MyDirectory;

@SpringBootTest
class ApplicationTests {

@Autowired
private MyDirectoryMapper myDirectoryMapper;

@Test
public void testQueryDirectoryById() {
MyDirectory myDirectory = myDirectoryMapper.selectByPrimaryKey(2);
System.out.println(myDirectory);
// 2022-06-18 11:53:48.895 INFO 2408 --- [ main] com.example.demo.ApplicationTests : Starting ApplicationTests using Java 1.8.0_271 on DESKTOP-IOB28AF with PID 2408 (started by Tom in E:\SpringToolSuite\project\demo-4.8.1\16_springboot_mybatis-2)
// 2022-06-18 11:53:48.896 INFO 2408 --- [ main] com.example.demo.ApplicationTests : No active profile set, falling back to 1 default profile: "default"
// 2022-06-18 11:53:49.412 INFO 2408 --- [ main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
// 2022-06-18 11:53:50.351 INFO 2408 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
// Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
// Parsed mapper file: 'file [E:\SpringToolSuite\project\demo-4.8.1\16_springboot_mybatis-2\target\classes\mapper\MyDirectoryMapper.xml]'
// 2022-06-18 11:53:50.775 INFO 2408 --- [ main] com.example.demo.ApplicationTests : Started ApplicationTests in 2.125 seconds (JVM running for 2.911)
// Creating a new SqlSession
// SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1bb15351] was not registered for synchronization because synchronization is not active
// JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@642413d4] will not be managed by Spring
// ==> Preparing: select directory_id, directory_name, remark, user_id from t_directory where directory_id = ?
// ==> Parameters: 2(Integer)
// <== Columns: directory_id, directory_name, remark, user_id
// <== Row: 2, usr, usr目录, 1
// <== Total: 1
// Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1bb15351]
// MyDirectory [directoryId=2, directoryName=usr, remark=usr目录, userId=1]
// 2022-06-18 11:53:51.065 INFO 2408 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ...
// 2022-06-18 11:53:51.069 INFO 2408 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed

}

}

4.使用PageHelper(引入依赖包)

(1) pom.xml,引入pageHelper的依赖包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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">

<dependencies>

<!-- pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.1</version>
</dependency>

</dependencies>

</project>

(2) 创建PageHelperAutoConfiguration类,向Spring容器中注入PageInterceptor对象

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

import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInterceptor;

@Configuration
@ConditionalOnClass(value = {PageHelper.class, MybatisAutoConfiguration.class})
public class PageHelperAutoConfiguration {

@Bean
public PageInterceptor pageInterceptor() {
return new PageInterceptor();
}

}

(3) 测试类

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

import java.util.List;

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

import com.example.demo.dao.MyDirectoryMapper;
import com.example.demo.entity.MyDirectory;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@SpringBootTest
class ApplicationTests {

@Autowired
private MyDirectoryMapper myDirectoryMapper;

@Test
public void testPageHelper1() {
Page<MyDirectory> page = PageHelper.startPage(1, 5);
List<MyDirectory> directoryList = myDirectoryMapper.getAllDirectory();
System.out.println(page.getTotal());
for (MyDirectory myDirectory : directoryList) {
System.out.println(myDirectory);
}

// 2022-06-18 13:38:44.414 INFO 6540 --- [ main] com.example.demo.ApplicationTests : Starting ApplicationTests using Java 1.8.0_271 on DESKTOP-IOB28AF with PID 6540 (started by Tom in E:\SpringToolSuite\project\demo-4.8.1\16_springboot_mybatis-2)
// 2022-06-18 13:38:44.415 INFO 6540 --- [ main] com.example.demo.ApplicationTests : No active profile set, falling back to 1 default profile: "default"
// 2022-06-18 13:38:44.955 INFO 6540 --- [ main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
// 2022-06-18 13:38:45.911 INFO 6540 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
// Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
// Registered plugin: 'com.github.pagehelper.PageInterceptor@27e5b378'
// Parsed mapper file: 'file [E:\SpringToolSuite\project\demo-4.8.1\16_springboot_mybatis-2\target\classes\mapper\MyDirectoryMapper.xml]'
// 2022-06-18 13:38:46.309 INFO 6540 --- [ main] com.example.demo.ApplicationTests : Started ApplicationTests in 2.138 seconds (JVM running for 2.919)
// Creating a new SqlSession
// SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@54067fdc] was not registered for synchronization because synchronization is not active
// Cache Hit Ratio [SQL_CACHE]: 0.0
// JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@141d3d43] will not be managed by Spring
// ==> Preparing: SELECT count(0) FROM t_directory
// ==> Parameters:
// <== Columns: count(0)
// <== Row: 16
// <== Total: 1
// ==> Preparing: select directory_id, directory_name, remark, user_id from t_directory LIMIT ?
// ==> Parameters: 5(Integer)
// <== Columns: directory_id, directory_name, remark, user_id
// <== Row: 1, home, home目录, 1
// <== Row: 2, usr, usr目录, 1
// <== Row: 3, source, source目录, 1
// <== Row: 4, tmp, tmp目录, 2
// <== Row: 5, bin, bin目录, 1
// <== Total: 5
// Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@54067fdc]
// total = 16
// MyDirectory [directoryId=1, directoryName=home, remark=home目录, userId=1]
// MyDirectory [directoryId=2, directoryName=usr, remark=usr目录, userId=1]
// MyDirectory [directoryId=3, directoryName=source, remark=source目录, userId=1]
// MyDirectory [directoryId=4, directoryName=tmp, remark=tmp目录, userId=2]
// MyDirectory [directoryId=5, directoryName=bin, remark=bin目录, userId=1]
// 2022-06-18 13:38:46.698 INFO 6540 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ...
// 2022-06-18 13:38:46.702 INFO 6540 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed

}

}

5.使用PageHelper(使用starter)

(1) pom.xml引入PageHelper starter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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">

<dependencies>

<!-- pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>

</dependencies>

</project>

(2) 测试类

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

import java.util.List;

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

import com.example.demo.dao.MyDirectoryMapper;
import com.example.demo.entity.MyDirectory;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@SpringBootTest
class ApplicationTests {

@Autowired
private MyDirectoryMapper myDirectoryMapper;

@Test
public void testPageHelper1() {
Page<MyDirectory> page = PageHelper.startPage(1, 5);
List<MyDirectory> directoryList = myDirectoryMapper.getAllDirectory();
System.out.println("total = " + page.getTotal());
for (MyDirectory myDirectory : directoryList) {
System.out.println(myDirectory);
}

// 2022-06-18 13:48:08.229 INFO 1224 --- [ main] com.example.demo.ApplicationTests : Starting ApplicationTests using Java 1.8.0_271 on DESKTOP-IOB28AF with PID 1224 (started by Tom in E:\SpringToolSuite\project\demo-4.8.1\17_springboot_mybatis-3)
// 2022-06-18 13:48:08.230 INFO 1224 --- [ main] com.example.demo.ApplicationTests : No active profile set, falling back to 1 default profile: "default"
// 2022-06-18 13:48:08.780 INFO 1224 --- [ main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
// 2022-06-18 13:48:09.765 INFO 1224 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
// Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
// Parsed mapper file: 'file [E:\SpringToolSuite\project\demo-4.8.1\17_springboot_mybatis-3\target\classes\mapper\MyDirectoryMapper.xml]'


// ,------. ,--. ,--. ,--.
// | .--. ' ,--,--. ,---. ,---. | '--' | ,---. | | ,---. ,---. ,--.--.
// | '--' | ' ,-. | | .-. | | .-. : | .--. | | .-. : | | | .-. | | .-. : | .--'
// | | --' \ '-' | ' '-' ' \ --. | | | | \ --. | | | '-' ' \ --. | |
// `--' `--`--' .`- / `----' `--' `--' `----' `--' | |-' `----' `--'
// `---' `--' is intercepting.

// 2022-06-18 13:48:10.206 INFO 1224 --- [ main] com.example.demo.ApplicationTests : Started ApplicationTests in 2.223 seconds (JVM running for 3.019)
// Creating a new SqlSession
// SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@54d1608f] was not registered for synchronization because synchronization is not active
// Cache Hit Ratio [SQL_CACHE]: 0.0
// JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2ae62bb6] will not be managed by Spring
// ==> Preparing: SELECT count(0) FROM t_directory
// ==> Parameters:
// <== Columns: count(0)
// <== Row: 16
// <== Total: 1
// ==> Preparing: select directory_id, directory_name, remark, user_id from t_directory LIMIT ?
// ==> Parameters: 5(Integer)
// <== Columns: directory_id, directory_name, remark, user_id
// <== Row: 1, home, home目录, 1
// <== Row: 2, usr, usr目录, 1
// <== Row: 3, source, source目录, 1
// <== Row: 4, tmp, tmp目录, 2
// <== Row: 5, bin, bin目录, 1
// <== Total: 5
// Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@54d1608f]
// total = 16
// MyDirectory [directoryId=1, directoryName=home, remark=home目录, userId=1]
// MyDirectory [directoryId=2, directoryName=usr, remark=usr目录, userId=1]
// MyDirectory [directoryId=3, directoryName=source, remark=source目录, userId=1]
// MyDirectory [directoryId=4, directoryName=tmp, remark=tmp目录, userId=2]
// MyDirectory [directoryId=5, directoryName=bin, remark=bin目录, userId=1]
// 2022-06-18 13:48:10.591 INFO 1224 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ...
// 2022-06-18 13:48:10.595 INFO 1224 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed

}

}