服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - Spring Boot+Mybatis+Pagehelper分页实现

Spring Boot+Mybatis+Pagehelper分页实现

2021-08-01 12:00xiaolyuh123 Java教程

本篇文章主要讲述的是Spring Boot+Mybatis+Pagehelper分页实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Spring Boot 集成MyBatis和Pagehelper分页插件

mybatis-spring-boot-starter依赖树如下:

Spring Boot+Mybatis+Pagehelper分页实现

pom配置

?
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
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.xiaolyuh</groupId>
  <artifactId>spring-boot-student-mybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>spring-boot-student-mybatis</name>
 
  <!-- 添加Spring Boot的父类依赖,这样当前项目就是Spring Boot项目了。 spring-boot-starter-parent是一个特殊的starter,他用来
    提供相关的maven默认依赖, 使用它之后,常用的依赖可以省去version标签 -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
 
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.0</version>
    </dependency>
    <!--pagehelper -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>1.1.1</version>
    </dependency>
 
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.31</version>
    </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>
      </plugin>
    </plugins>
  </build>
 
</project>

application.properties配置

?
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
server.port=80
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/ssb_test
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
#连接池配置
#spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
 
#mybatis
#entity扫描的包名
mybatis.type-aliases-package=com.xiaolyuh.domain.model
#Mapper.xml所在的位置
mybatis.mapper-locations=classpath*:/mybaits/*Mapper.xml
 
#pagehelper分页插件配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
 
#日志配置
logging.level.com.xiaolyuh=debug
logging.level.org.springframework.web=debug
logging.level.org.springframework.transaction=debug
logging.level.org.mybatis=debug
 
debug=false

除了上面常见的两项配置,还有:

?
1
2
3
4
mybatis.config-location=mybatis-config.xml配置文件的路径
mybatis.type-handlers-package=扫描typeHandlers的包
mybatis.check-config-location=检查配置文件是否存在
mybatis.executor-type=设置执行模式(SIMPLE, REUSE, BATCH),默认为SIMPLE

Mapping XML文件

在resources文件夹下创建mybaits/PersonMapper.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?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.xiaolyuh.domain.mapper.PersonMapper" >
 <resultMap id="BaseResultMap" type="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  <id column="id" property="id" jdbcType="BIGINT" />
  <result column="name" property="name" jdbcType="VARCHAR" />
  <result column="age" property="age" jdbcType="INTEGER" />
  <result column="address" property="address" jdbcType="VARCHAR" />
 </resultMap>
 <sql id="Base_Column_List" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  id, name, age, address
 </sql>
 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  select
  <include refid="Base_Column_List" />
  from person
  where id = #{id,jdbcType=BIGINT}
 </select>
 <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  delete from person
  where id = #{id,jdbcType=BIGINT}
 </delete>
 <insert id="insert" parameterType="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
   SELECT LAST_INSERT_ID()
  </selectKey>
  insert into person (name, age, address
   )
  values (#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{address,jdbcType=VARCHAR}
   )
 </insert>
 <insert id="insertSelective" parameterType="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
   SELECT LAST_INSERT_ID()
  </selectKey>
  insert into person
  <trim prefix="(" suffix=")" suffixOverrides="," >
   <if test="name != null" >
    name,
   </if>
   <if test="age != null" >
    age,
   </if>
   <if test="address != null" >
    address,
   </if>
  </trim>
  <trim prefix="values (" suffix=")" suffixOverrides="," >
   <if test="name != null" >
    #{name,jdbcType=VARCHAR},
   </if>
   <if test="age != null" >
    #{age,jdbcType=INTEGER},
   </if>
   <if test="address != null" >
    #{address,jdbcType=VARCHAR},
   </if>
  </trim>
 </insert>
 <update id="updateByPrimaryKeySelective" parameterType="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  update person
  <set >
   <if test="name != null" >
    name = #{name,jdbcType=VARCHAR},
   </if>
   <if test="age != null" >
    age = #{age,jdbcType=INTEGER},
   </if>
   <if test="address != null" >
    address = #{address,jdbcType=VARCHAR},
   </if>
  </set>
  where id = #{id,jdbcType=BIGINT}
 </update>
 <update id="updateByPrimaryKey" parameterType="com.xiaolyuh.domain.model.Person" >
  <!--
   WARNING - @mbggenerated
   This element is automatically generated by MyBatis Generator, do not modify.
  -->
  update person
  set name = #{name,jdbcType=VARCHAR},
   age = #{age,jdbcType=INTEGER},
   address = #{address,jdbcType=VARCHAR}
  where id = #{id,jdbcType=BIGINT}
 </update>
 
 <select id="findAll" resultMap="BaseResultMap">
  select
  <include refid="Base_Column_List" />
  from person
 </select>
 
 <select id="findByPage" resultMap="BaseResultMap">
  select
  <include refid="Base_Column_List" />
  from person
 </select>
</mapper>

DAO层Mapper类

在Mapper接口上需要加上@Mapper注解,@Mapper注解声明成mybatis Dao层的Bean。也可以在配置类上使用@MapperScan("com.xiaolyuh.domain.mapper")注解声明。

?
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
package com.xiaolyuh.domain.mapper;
 
import com.github.pagehelper.Page;
import com.xiaolyuh.domain.model.Person;
import org.apache.ibatis.annotations.Mapper;
 
import java.util.List;
 
@Mapper//声明成mybatis Dao层的Bean,也可以在配置类上使用@MapperScan("com.xiaolyuh.domain.mapper")注解声明
public interface PersonMapper {
 
  int deleteByPrimaryKey(Long id);
 
  int insert(Person record);
 
  int insertSelective(Person record);
 
  Person selectByPrimaryKey(Long id);
 
  int updateByPrimaryKeySelective(Person record);
 
  int updateByPrimaryKey(Person record);
 
  /**
   * 获取所有数据
   * @return
   */
  List<Person> findAll();
 
  /**
   * 分页查询数据
   * @return
   */
  Page<Person> findByPage();
}

实体类

?

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
package com.xiaolyuh.domain.model;
 
public class Person {
 
  private Long id;
 
  /**
   * 名称
   */
  private String name;
 
  /**
   * 年龄
   */
  private Integer age;
 
  /**
   * 地址
   */
  private String address;
 
  public Long getId() {
    return id;
  }
 
  public void setId(Long id) {
    this.id = id;
  }
 
  public String getName() {
    return name;
  }
 
  public void setName(String name) {
    this.name = name;
  }
 
  public Integer getAge() {
    return age;
  }
 
  public void setAge(Integer age) {
    this.age = age;
  }
 
  public String getAddress() {
    return address;
  }
 
  public void setAddress(String address) {
    this.address = address;
  }
}

Service层

接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.xiaolyuh.service;
 
import com.github.pagehelper.Page;
import com.xiaolyuh.domain.model.Person;
 
import java.util.List;
 
/**
 * Created by yuhao.wang on 2017/6/19.
 */
public interface PersonService {
 
  List<Person> findAll();
 
  /**
   * 分页查询
   * @param pageNo 页号
   * @param pageSize 每页显示记录数
   * @return
   */
  Page<Person> findByPage(int pageNo, int pageSize);
 
  void insert(Person person);
}

实现类

?
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
package com.xiaolyuh.service.impl;
 
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaolyuh.domain.mapper.PersonMapper;
import com.xiaolyuh.domain.model.Person;
import com.xiaolyuh.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.List;
 
/**
 * Created by yuhao.wang on 2017/6/19.
 */
@Service
@Transactional(readOnly = true)
public class PersonServiceImpl implements PersonService {
 
  @Autowired
  private PersonMapper personMapper;
 
  @Override
  public List<Person> findAll() {
    return personMapper.findAll();
  }
 
  @Override
  public Page<Person> findByPage(int pageNo, int pageSize) {
    PageHelper.startPage(pageNo, pageSize);
    return personMapper.findByPage();
  }
 
  @Override
  @Transactional
  public void insert(Person person) {
    personMapper.insert(person);
  }
 
}

分页的包装类PageInfo

需要把Page包装成PageInfo对象才能序列化。该插件也默认实现了一个PageInfo

?
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package com.xiaolyuh.page;
 
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
 
import com.github.pagehelper.Page;
 
/**
 * 对Page<E>结果进行包装
 * <p/>
 * 新增分页的多项属性,主要参考:http://bbs.csdn.net/topics/360010907
 *
 * @author liuzh/abel533/isea533
 * @version 3.3.0
 * @since 3.2.2
 * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class PageInfo<T> implements Serializable {
  private static final long serialVersionUID = 1L;
  //当前页
  private int pageNum;
  //每页的数量
  private int pageSize;
  //总记录数
  private long total;
  //总页数
  private int pages;
  //结果集
  private List<T> list;
  //是否为第一页
  private boolean isFirstPage = false;
  //是否为最后一页
  private boolean isLastPage = false;
 
 
  public PageInfo() {
  }
 
  /**
   * 包装Page对象
   *
   * @param list
   */
  public PageInfo(List<T> list) {
    if (list instanceof Page) {
      Page page = (Page) list;
      this.pageNum = page.getPageNum();
      this.pageSize = page.getPageSize();
 
      this.pages = page.getPages();
      this.list = page;
      this.total = page.getTotal();
    } else if (list instanceof Collection) {
      this.pageNum = 1;
      this.pageSize = list.size();
 
      this.pages = 1;
      this.list = list;
      this.total = list.size();
    }
    if (list instanceof Collection) {
      //判断页面边界
      judgePageBoudary();
    }
  }
 
  /**
   * 判定页面边界
   */
  private void judgePageBoudary() {
    isFirstPage = pageNum == 1;
    isLastPage = pageNum == pages;
  }
 
  public int getPageNum() {
    return pageNum;
  }
 
  public void setPageNum(int pageNum) {
    this.pageNum = pageNum;
  }
 
  public int getPageSize() {
    return pageSize;
  }
 
  public void setPageSize(int pageSize) {
    this.pageSize = pageSize;
  }
 
  public long getTotal() {
    return total;
  }
 
  public void setTotal(long total) {
    this.total = total;
  }
 
  public int getPages() {
    return pages;
  }
 
  public void setPages(int pages) {
    this.pages = pages;
  }
 
  public List<T> getList() {
    return list;
  }
 
  public void setList(List<T> list) {
    this.list = list;
  }
 
  public boolean isIsFirstPage() {
    return isFirstPage;
  }
 
  public void setIsFirstPage(boolean isFirstPage) {
    this.isFirstPage = isFirstPage;
  }
 
  public boolean isIsLastPage() {
    return isLastPage;
  }
 
  public void setIsLastPage(boolean isLastPage) {
    this.isLastPage = isLastPage;
  }
 
  @Override
  public String toString() {
    final StringBuffer sb = new StringBuffer("PageInfo{");
    sb.append("pageNum=").append(pageNum);
    sb.append(", pageSize=").append(pageSize);
    sb.append(", total=").append(total);
    sb.append(", pages=").append(pages);
    sb.append(", list=").append(list);
    sb.append(", isFirstPage=").append(isFirstPage);
    sb.append(", isLastPage=").append(isLastPage);
    sb.append(", navigatepageNums=");
    sb.append('}');
    return sb.toString();
  }
}

测试类

?
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
package com.xiaolyuh;
 
import com.github.pagehelper.Page;
import com.xiaolyuh.domain.model.Person;
import com.xiaolyuh.page.PageInfo;
import com.xiaolyuh.service.PersonService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
import java.util.List;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonMapperTests {
 
 private Logger logger = LoggerFactory.getLogger(PersonMapperTests.class);
 
 @Autowired
 private PersonService personService;
 
 @Before
 public void testInsert() {
 Person person = new Person();
 person.setName("测试");
 person.setAddress("address");
 person.setAge(10);
 personService.insert(person);
 
 Assert.assertNotNull(person.getId());
 logger.debug(JSON.toJSONString(person));
 }
 
 @Test
 public void testFindAll() {
 List<Person> persons = personService.findAll();
 
 Assert.assertNotNull(persons);
 logger.debug(JSON.toJSONString(persons));
 }
 
 @Test
 public void testFindByPage() {
 Page<Person> persons = personService.findByPage(1, 2);
 // 需要把Page包装成PageInfo对象才能序列化。该插件也默认实现了一个PageInfo
 PageInfo<Person> pageInfo = new PageInfo<>(persons);
 Assert.assertNotNull(persons);
 logger.debug(pageInfo.toString());
 logger.debug(JSON.toJSONString(pageInfo));
 }
 
 @Test
 public void testCacheByPage() {
 long begin = System.currentTimeMillis();
 List<Person> persons = personService.findAll();
 long ing = System.currentTimeMillis();
 personService.findAll();
 long end = System.currentTimeMillis();
 logger.debug("第一次请求时间:" + (ing - begin) + "ms");
 logger.debug("第二次请求时间:" + (end - ing) + "ms");
 
 Assert.assertNotNull(persons);
 logger.debug(persons.toString());
 logger.debug(JSON.toJSONString(persons));
 }
 
}

源码

https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases

到此这篇关于Spring Boot+Mybatis+Pagehelper分页实现的文章就介绍到这了,更多相关Spring Boot+Mybatis+Pagehelper分页内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/xiaolyuh123/article/details/73506189

延伸 · 阅读

精彩推荐
  • Java教程shiro编码和加密代码详解

    shiro编码和加密代码详解

    Shiro提供了base64和16进制字符串编码/解码的API支持,方便一些编码解码操作。下面通过实例代码给大家详解shiro编码和加密知识,感兴趣的朋友一起看看吧...

    动力节点4012021-01-06
  • Java教程详解Java注解教程及自定义注解

    详解Java注解教程及自定义注解

    这篇文章主要为大家详细介绍了Java注解教程及自定义注解,帮助大家更好地学习Java注解,感兴趣的小伙伴们可以参考一下 ...

    lijiao2752020-03-24
  • Java教程爬虫技术详解

    爬虫技术详解

    本文全面的介绍了爬虫的原理、技术现状、以及目前仍面临的问题。具有很好的参考价值。下面跟着小编一起来看下吧...

    落叶的博客1632020-08-27
  • Java教程jdbc实现连接和增删改查功能

    jdbc实现连接和增删改查功能

    这篇文章主要为大家详细介绍了jdbc实现连接和基本的增删改查功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    lxh54318182021-07-16
  • Java教程教你轻松制作java音乐播放器

    教你轻松制作java音乐播放器

    这篇文章主要介绍了如何编写属于自己的java音乐播放器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Java开发网5772020-06-28
  • Java教程Maven镜像地址配置示例大全

    Maven镜像地址配置示例大全

    这篇文章主要介绍了Maven镜像地址配置示例大全,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧 ...

    csdn-华仔4742020-07-01
  • Java教程Spring高阶用法之自定义业务对象组件化

    Spring高阶用法之自定义业务对象组件化

    这篇文章主要介绍了Spring高阶用法之自定义业务对象组件化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    seeing10692021-07-24
  • Java教程java线程间通信的通俗解释及代码示例

    java线程间通信的通俗解释及代码示例

    这篇文章主要介绍了java线程间通信的通俗解释,介绍了线程通信中的几个相关概念,然后分享了线程通信的实现方式及代码示例,具有一定参考价值 ,需...

    爱折腾的猫9292021-02-07