依赖配置可参考:MyBatis-Plus学习笔记(1):环境搭建以及基本的CRUD操作
分页配置
代码语言:javascript复制@Configuration
public class PlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
通用Mapper查询分页
代码语言:javascript复制 @Test
public void testSelectPage(){
//分页对象,构造函数传入当前页数和每页条数
Page selectPage = new Page<User>(1, 10);
//是否查询总条数,默认为true,也可以通过构造函数传入
//selectPage.setSearchCount(false);
//封装查询条件
Wrapper wrapper = new QueryWrapper<User>().gt("id", 0).orderByDesc("id");
//调用通用Mapper
Page<User> resultPage = userMapper.selectPage(selectPage, wrapper);
System.out.println("总条数:" resultPage.getTotal());
System.out.println("列表:" resultPage.getRecords());
//true,返回的对象和查询时传入的对象是同一个对象
System.out.println(selectPage.equals(resultPage));
}
自定义Mapper查询分页
UserMapper.java:
代码语言:javascript复制package com.cf.plusdm.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cf.plusdm.entity.User;
public interface UserMapper extends BaseMapper<User> {
IPage<User> getUserList(Page<User> page);
}
UserMapper.xml:
代码语言:javascript复制<?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.cf.plusdm.mapper.UserMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.cf.plusdm.entity.User">
<id column="id" property="id" />
<result column="real_name" property="realName" />
<result column="email" property="email" />
<result column="phone" property="phone" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
id, real_name, email, phone
</sql>
<select id="getUserList" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"></include>
FROM tb_user
</select>
</mapper>
使用:
代码语言:javascript复制 @Test
public void testSelectPageXml(){
Page resultPage = new Page<User>(1, 10);
userMapper.getUserList(resultPage);
System.out.println("总条数:" resultPage.getTotal());
System.out.println("列表:" resultPage.getRecords());
}
参考:分页插件