Perfree

Perfree

Perfree

简简单单的生活,安安静静的写博客~

54 文章数
72 评论数

SpringBoot-整合Mybatis分页插件-PageHelper

perfree
2019-01-04 / 0 评论 / 2378 阅读 / 0 点赞

Mybatis的一个插件,PageHelper,非常方便mybatis分页查询。国内牛人的一个开源项目,有兴趣的可以去看源码,都有中文注释,Github地址Mybatis-PageHelper,接下来就利用SpringBoot整合下Pagehelper分页插件,其实官方给了整合教程,有兴趣的可以去看看MyBatis-Spring-Boot,话不多说,下面开始整合,本实例Github地址06-mybatis-pagehelper

数据库

/*
Navicat MySQL Data Transfer

Source Server         : perfree-pc
Source Server Version : 50621
Source Host           : localhost:3306
Source Database       : springboot

Target Server Type    : MYSQL
Target Server Version : 50621
File Encoding         : 65001

Date: 2018-10-03 10:18:50
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(50) DEFAULT NULL COMMENT '姓名',
  `age` int(11) DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '张三', '21');
INSERT INTO `user` VALUES ('2', '李四', '23');
INSERT INTO `user` VALUES ('3', '王二', '22');
INSERT INTO `user` VALUES ('4', '陈某', '25');
INSERT INTO `user` VALUES ('5', '刘某', '20');

pom文件

先来个完整的pom文件

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.perfree</groupId>
    <artifactId>mybatis-pagehelper</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mybatis-pagehelper</name>
    <description>SpringBoot-Mybatis-Pagehelper</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.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-web</artifactId>
        </dependency>
        <!-- SpringBoot-mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.2.4</version>
        </dependency>
        <!--pagehelper-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!--数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</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>

关键依赖:

<!-- SpringBoot-mybatis依赖 -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.2</version>
</dependency>
<!--mapper-->
<dependency>
	<groupId>tk.mybatis</groupId>
	<artifactId>mapper-spring-boot-starter</artifactId>
	<version>1.2.4</version>
</dependency>
<!--pagehelper-->
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper-spring-boot-starter</artifactId>
	<version>1.2.3</version>
</dependency>
<!--数据库驱动 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.39</version>
</dependency>

项目结构一览

PageResult为分页查询结果集

pojo实体类

package com.perfree.mybatispagehelper.pojo;

/**
 * @ClassName User
 * @Description TODO(user实体类)
 * @Author Perfree
 * @Date 2018/10/3 10:19
 * @Version 1.0
 */
public class User {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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;
    }
}

Controller

package com.perfree.mybatispagehelper.controller;

import com.perfree.mybatispagehelper.common.PageResult;
import com.perfree.mybatispagehelper.pojo.User;
import com.perfree.mybatispagehelper.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @ClassName UserController
 * @Description TODO(userController)
 * @Author Perfree
 * @Date 2018/10/3 10:20
 * @Version 1.0
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/users/{page}/{pageSize}")
    public PageResult<User> getUserByPage(@PathVariable Integer page, @PathVariable Integer pageSize){
        System.out.println(page+"  "+pageSize);
        PageResult<User> result = userService.getUserByPage(page,pageSize);
        return result;
    }
}

Service接口

package com.perfree.mybatispagehelper.service;

import com.perfree.mybatispagehelper.common.PageResult;
import com.perfree.mybatispagehelper.pojo.User;

import java.util.List;

/**
 * @ClassName UserService
 * @Description TODO(userService 接口)
 * @Author Perfree
 * @Date 2018/10/3 10:20
 * @Version 1.0
 */
public interface UserService {
    PageResult<User> getUserByPage(Integer page, Integer pageSize);
}

PageResult 分页结果集

package com.perfree.mybatispagehelper.common;

import java.util.List;

/**
 * @ClassName PageResult
 * @Description TODO(分页结果)
 * @Author Perfree
 * @Date 2018/10/3 10:30
 * @Version 1.0
 */
public class PageResult<T> {
    //共有数据条数
    private Long total;
    //共有页数
    private Integer pageTotal;
    //当前页
    private Integer page;
    //每页显示多杀条
    private Integer pageSize;
    //结果集
    private List<T> list;

    public Long getTotal() {
        return total;
    }

    public void setTotal(Long total) {
        this.total = total;
    }

    public Integer getPageTotal() {
        return pageTotal;
    }

    public void setPageTotal(Integer pageTotal) {
        this.pageTotal = pageTotal;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }
}

Service实现类

package com.perfree.mybatispagehelper.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.perfree.mybatispagehelper.common.PageResult;
import com.perfree.mybatispagehelper.mapper.UserMapper;
import com.perfree.mybatispagehelper.pojo.User;
import com.perfree.mybatispagehelper.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Description TODO(UserService 实现)
 * @Author Perfree
 * @Date 2018/10/3 10:24
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult<User> getUserByPage(Integer page, Integer pageSize) {
        //设置起始页,每页显示的数量
        PageHelper.startPage(page,pageSize);
        //查询
        List<User> list = userMapper.getAllUser();
        //将查询的结果给pageinfo处理
        PageInfo<User> pageInfo = new PageInfo<>(list);
        //创建结果集对象
        PageResult<User> result = new PageResult<>();
        //将结果封装到结果集对象中
        //当前页
        result.setPage(page);
        //每页的数量
        result.setPageSize(pageInfo.getPageSize());
        //总页数
        result.setPageTotal(pageInfo.getPages());
        //总条数
        result.setTotal(pageInfo.getTotal());
        //结果集
        result.setList(pageInfo.getList());
        return result;
    }
}

mapper接口

package com.perfree.mybatispagehelper.mapper;

import com.perfree.mybatispagehelper.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @ClassName UserMapper
 * @Description TODO(UserMapper 接口)
 * @Author Perfree
 * @Date 2018/10/3 10:24
 * @Version 1.0
 */
@Mapper
public interface UserMapper {

    List<User> getAllUser();
}

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.perfree.mybatispagehelper.mapper.UserMapper">
    <select id="getAllUser" resultType="com.perfree.mybatispagehelper.pojo.User">
        select id,name,age from user
    </select>
</mapper>

application.properties配置

## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=215521
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

## Mybatis 配置
mybatis.typeAliasesPackage=com.perfree.mybatis.pojo.User
mybatis.mapperLocations=classpath:mapper/*.xml

#mapper
#mappers 多个接口时逗号隔开
mapper.mappers=com.perfree.mybatispagehelper.mapper.UserMapper
mapper.not-empty=false
mapper.identity=MYSQL

#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

程序入口开启包扫描

package com.perfree.mybatispagehelper;

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

@MapperScan("com.perfree.mybatispagehelper.mapper.UserMapper")
@SpringBootApplication
public class MybatisPagehelperApplication {

    public static void main(String[] args) {

        SpringApplication.run(MybatisPagehelperApplication.class, args);
    }

}

运行

1.查询第一页,每页显示3条url: http://127.0.0.1:8080/users/1/3 结果:

{
	"total":5,
	"pageTotal":2,
	"page":1,
	"pageSize":3,
	"list":[{"id":1,"name":"张三","age":21},{"id":2,"name":"李四","age":23},{"id":3,"name":"王二","age":22}]}

2.查询第一页,每页显示2条url: http://127.0.0.1:8080/users/1/2 结果:

{
	"total":5,
	"pageTotal":3,
	"page":1,
	"pageSize":2,
	"list":[{"id":1,"name":"张三","age":21},{"id":2,"name":"李四","age":23}]}
文章不错,扫码支持一下吧~
上一篇 下一篇
评论
来首音乐
最新回复
光阴似箭
今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月