MybatisPlus实现分页处理数据

Mybatis 分页

说明:使用MybatisPlus官网中的插件主体,进行实现我们的分页查询

1、添加插件主体的类

在自己config的包中配置这个插件。

@Configuration
public class MybatisPlusConfig {
          
   

    /**
     * 插件
     * @return
     */
    @Bean
    public MybatisPlusInterceptor addPaginationInnerInterceptor(){
          
   
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //向Mybatis过滤器链中添加分页拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

2、编写自己的Controller

说明:分页的实现无非就是传两个参数(1、当前页 2、每页显示多少数据),通过RestFul风格进行实现就可以了。

分页controller

@ApiOperation(value = "获取分页列表")
@GetMapping("/{page}/{limit}")
public Result index(
        @ApiParam(name = "page", value = "当前页码", required = true)
        @PathVariable Long page,

        @ApiParam(name = "limit", value = "每页记录数", required = true)
        @PathVariable Long limit,

        @ApiParam(name = "roleQueryVo", value = "查询对象", required = false)
                SysRoleQueryVo roleQueryVo) {
          
   
	//创建一个Page对象
    Page<SysRole> pageParam = new Page<>(page, limit);

	//调用service方法
    IPage<SysRole> pageModel = sysRoleService.selectPage(pageParam, roleQueryVo);
	
	//返回数据
    return Result.ok(pageModel);
}

Service

IPage<SysRole> selectPage(Page<SysRole> pageParam, SysRoleQueryVo roleQueryVo);
@Override
public IPage<SysRole> selectPage(Page<SysRole> pageParam, SysRoleQueryVo roleQueryVo) {
          
   

    return sysRoleMapper.selectPage(pageParam, roleQueryVo);
}

pojo

import java.io.Serializable;

/**
 * <p>
 * 角色查询实体
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
public class SysRoleQueryVo implements Serializable {
          
   
	
	private static final long serialVersionUID = 1L;
	
	private String roleName;

	public String getRoleName() {
          
   
		return roleName;
	}

	public void setRoleName(String roleName) {
          
   
		this.roleName = roleName;
	}
}

Mapper

IPage<SysRole> selectPage(Page<SysRole> page, @Param("vo") SysRoleQueryVo roleQueryVo);

XML 在resources目录下创建mapper/SysRoleMapper.xml文件

说明:分页我们统一定义到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.atguigu.system.mapper.SysRoleMapper">
	
	 <!-- 自动映射 -->
    <resultMap id="RoleMap" type="com.atguigu.model.system.SysRole" autoMapping="true">
    </resultMap>

    <!-- 用于select查询公用抽取的列 -->
    <sql id="columns">
        id,role_name,role_code,description,create_time,update_time,is_deleted
    </sql>

    <select id="selectPage" resultMap="RoleMap">
        select <include refid="columns" />
        from sys_role
        <where>
            <if test="vo.roleName != null and vo.roleName != ">
                and role_name like CONCAT(%,#{vo.roleName},%)
            </if>
            and is_deleted = 0
        </where>
        order by id desc
    </select>

</mapper>
经验分享 程序员 微信小程序 职场和发展