注:详细请看2.X博客中,3.X直接上代码。

建议装一个MybatisX插件,可以在Mapper和Xml来回切换

  • pom.xml

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
<scope>test</scope>
</dependency>
<!-- for testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
  • 配置类

    @Configuration
    @MapperScan("com.mp.pagination.mapper")
    public class MybatisPlusConfig {

    /**
    * 分页插件
    */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
    // 开启 count 的 join 优化,只针对 left join !!!
    return new PaginationInterceptor().setCountSqlParser(new JsqlParserCountOptimize(true));
    }
    }
  • application.yml

    # DataSource Config
    spring:
    datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:tcp://192.168.180.115:19200/~/mem/test
    username: root
    password: test

    # Logger Config
    logging:
    level:
    com.mp.pagination: debug

    mybatis-plus:
    mapper-locations: classpath:/mapper/*Mapper.xml
  • 实体类

    @Data
    public class Children {
    private Long id;
    private String name;
    private Long userId;
    }

    @Data
    public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
    }
  • Dao层

    public interface UserMapper extends BaseMapper<User> {

    /**
    * 3.x 的 page 可以进行取值,多个入参记得加上注解
    * 自定义 page 类必须放在入参第一位
    * 返回值可以用 IPage<T> 接收 也可以使用入参的 MyPage<T> 接收
    * <li> 3.1.0 之前的版本使用注解会报错,写在 xml 里就没事 </li>
    * <li> 3.1.0 开始支持注解,但是返回值只支持 IPage ,不支持 IPage 的子类</li>
    *
    * @param myPage 自定义 page
    * @return 分页数据
    */
    // @Select("select * from user where (age = #{pg.selectInt} and name = #{pg.selectStr}) or (age = #{ps.yihao} and name = #{ps.erhao})")
    MyPage<User> mySelectPage(@Param("pg") MyPage<User> myPage, @Param("ps") ParamSome paramSome);


    @ResultMap("userChildrenMap")
    @Select("<script>select u.id,u.name,u.email,u.age,c.id as \"c_id\",c.name as \"c_name\",c.user_id as \"c_user_id\" " +
    "from user u " +
    "left join children c on c.user_id = u.id " +
    "<where>" +
    "<if test=\"selectInt != null\"> " +
    "and u.age = #{selectInt} " +
    "</if> " +
    "<if test=\"selectStr != null and selectStr != ''\"> " +
    "and c.name = #{selectStr} " +
    "</if> " +
    "</where>" +
    "</script>")
    MyPage<UserChildren> userChildrenPage(MyPage<UserChildren> myPage);


    MyPage<User> mySelectPageMap(@Param("pg") MyPage<User> myPage, @Param("map") Map param);

    List<User> mySelectMap(Map param);

    List<User> myPageSelect(MyPage<User> myPage);

    List<User> iPageSelect(IPage<User> myPage);

    List<User> rowBoundList(RowBounds rowBounds, Map map);
    }
  • model层

    @Data
    @Accessors(chain = true)
    @EqualsAndHashCode(callSuper = true)
    public class MyPage<T> extends Page<T> {
    private static final long serialVersionUID = 5194933845448697148L;

    private Integer selectInt;
    private String selectStr;
    private String name;

    public MyPage(long current, long size) {
    super(current, size);
    }
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class ParamSome {

    private Integer yihao;
    private String erhao;
    }

    @Data
    @ToString(callSuper = true)
    @EqualsAndHashCode(callSuper = true)
    public class UserChildren extends User {

    private List<Children> c;
    }
  • 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.mp.pagination.mapper.UserMapper">

    <resultMap id="userChildrenMap" type="com.mp.pagination.model.UserChildren">
    <id column="id" property="id"/>
    <result column="age" property="age"/>
    <result column="email" property="email"/>
    <result column="name" property="name"/>
    <collection property="c" ofType="com.mp.pagination.entity.Children" columnPrefix="c_">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="user_id" property="userId"/>
    </collection>
    </resultMap>

    <select id="mySelectPage" resultType="com.mp.pagination.entity.User">
    select *
    from user
    where (age = #{pg.selectInt} and name = #{pg.selectStr})
    or (age = #{ps.yihao} and name = #{ps.erhao})
    </select>

    <select id="mySelectPageMap" resultType="com.mp.pagination.entity.User">
    select * from user
    <where>
    <if test="map.name!=null and map.name!=''">
    name like #{map.name}
    </if>
    </where>
    </select>

    <select id="mySelectMap" resultType="com.mp.pagination.entity.User">
    select * from user
    <where>
    <if test="name!=null and name!=''">
    name like #{name}
    </if>
    </where>
    </select>

    <select id="myPageSelect" resultType="com.mp.pagination.entity.User">
    select * from user
    <where>
    <if test="name!=null and name!=''">
    name like '%'||#{name}||'%'
    </if>
    </where>
    </select>

    <select id="iPageSelect" resultType="com.mp.pagination.entity.User">
    select * from user
    <where>
    <if test="name!=null and name!=''">
    name like #{name}
    </if>
    </where>
    </select>

    <select id="rowBoundList" resultType="com.mp.pagination.entity.User">
    select * from user
    <where>
    <if test="name!=null and name!=''">
    name like #{name}
    </if>
    </where>
    </select>
    </mapper>
  • 测试类

    注:这里的MyPage对Page做了一层嵌套,其实一般不用,都是通过实体类的参数带到SQL中

    @RunWith(SpringRunner.class)
    @SpringBootTest
    class PaginationApplicationTests {

    @Resource
    private UserMapper mapper;

    @Test
    public void lambdaPagination() {
    Page<User> page = new Page<>(1, 3);
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.lambda().ge(User::getAge, 1).orderByAsc(User::getAge);
    IPage<User> result = mapper.selectPage(page, wrapper);
    System.out.println(result.getTotal());
    Assert.assertTrue(result.getTotal() > 3);
    Assert.assertEquals(3, result.getRecords().size());
    }

    @Test
    public void tests1() {
    System.out.println("----- baseMapper 自带分页 ------");
    Page<User> page = new Page<>(1, 5);
    IPage<User> userIPage = mapper.selectPage(page, new QueryWrapper<User>()
    .eq("age", 20).eq("name", "Jack"));
    // assertThat(page).isSameAs(userIPage);
    System.out.println("总条数 ------> " + userIPage.getTotal());
    System.out.println("当前页数 ------> " + userIPage.getCurrent());
    System.out.println("当前每页显示数 ------> " + userIPage.getSize());
    print(userIPage.getRecords());
    System.out.println("----- baseMapper 自带分页 ------");

    System.out.println("json 正反序列化 begin");
    String json = JSON.toJSONString(page);
    Page<User> page1 = JSON.parseObject(json, Page.class);
    print(page1.getRecords());
    System.out.println("json 正反序列化 end");

    System.out.println("----- 自定义 XML 分页 ------");
    MyPage<User> myPage = new MyPage<User>(1, 5).setSelectInt(20).setSelectStr("Jack");
    ParamSome paramSome = new ParamSome(20, "Jack");
    MyPage<User> userMyPage = mapper.mySelectPage(myPage, paramSome);
    //assertThat(myPage).isSameAs(userMyPage);
    System.out.println("总条数 ------> " + userMyPage.getTotal());
    System.out.println("当前页数 ------> " + userMyPage.getCurrent());
    System.out.println("当前每页显示数 ------> " + userMyPage.getSize());
    print(userMyPage.getRecords());
    System.out.println("----- 自定义 XML 分页 ------");
    }

    @Test
    public void tests2() {
    /* 下面的 left join 不会对 count 进行优化,因为 where 条件里有 join 的表的条件 */
    MyPage<UserChildren> myPage = new MyPage<>(1, 5);
    myPage.setSelectInt(18).setSelectStr("Jack");
    MyPage<UserChildren> userChildrenMyPage = mapper.userChildrenPage(myPage);
    List<UserChildren> records = userChildrenMyPage.getRecords();
    records.forEach(System.out::println);

    /* 下面的 left join 会对 count 进行优化,因为 where 条件里没有 join 的表的条件 */
    myPage = new MyPage<UserChildren>(1, 5).setSelectInt(18);
    userChildrenMyPage = mapper.userChildrenPage(myPage);
    records = userChildrenMyPage.getRecords();
    records.forEach(System.out::println);
    }

    private <T> void print(List<T> list) {
    if (!CollectionUtils.isEmpty(list)) {
    list.forEach(System.out::println);
    }
    }


    @Test
    public void testMyPageMap() {
    MyPage<User> myPage = new MyPage<User>(1, 5).setSelectInt(20).setSelectStr("Jack");
    Map map = new HashMap(1);
    map.put("name", "%a");
    mapper.mySelectPageMap(myPage, map);
    myPage.getRecords().forEach(System.out::println);
    }

    @Test
    public void testMap() {
    Map map = new HashMap(1);
    map.put("name", "%a");
    mapper.mySelectMap(map).forEach(System.out::println);
    }

    @Test
    public void myPage() {
    MyPage<User> page = new MyPage<>(1, 5);
    page.setName("a");
    mapper.myPageSelect(page).forEach(System.out::println);
    }

    @Test
    public void iPageTest() {
    IPage<User> page = new Page<User>(1, 5) {
    private String name = "%";

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }
    };

    List<User> list = mapper.iPageSelect(page);
    System.out.println("list.size=" + list.size());
    System.out.println("page.total=" + page.getTotal());
    }

    @Test
    public void rowBoundsTest() {
    RowBounds rowBounds = new RowBounds(0, 5);
    Map map = new HashMap(1);
    map.put("name", "%");
    List<User> list = mapper.rowBoundList(rowBounds, map);
    System.out.println("list.size=" + list.size());
    }

    }
     

SpringBoot整合MybatisPlus3.X之分页插件(四)的更多相关文章

  1. SpringBoot-07:SpringBoot整合PageHelper做多条件分页查询

    ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 本篇博客讲述如何在SpringBoot中整合PageHelper,如何实现带多个条件,以及PageInfo中的 ...

  2. SpringBoot整合PageHelper做多条件分页查询

    https://yq.aliyun.com/articles/619586 本篇博客讲述如何在SpringBoot中整合PageHelper,如何实现带多个条件,以及PageInfo中的属性的中文解释 ...

  3. SpringBoot整合MyBatis-Plus3.1详细教程

    作者:Sans_ juejin.im/post/5cfa6e465188254ee433bc69 一.说明 Mybatis-Plus是一个Mybatis框架的增强插件,根据官方描述,MP只做增强不做改 ...

  4. SpringBoot 整合Mybatis + PageHelper 实现分页

    前言: 现在公司大多数都实现了前后端分离,前端使用Vue.React.AngularJS 等框架,不用完全依赖后端.但是如果对于比较小型的项目,没必要前后端分离,而SpringBoot也基本抛弃了Js ...

  5. SpringBoot+MyBatis多数据源使用分页插件PageHelper

    之前只用过单数据源下的分页插件,而且几乎不用配置.一个静态方法就能搞定. PageHelper.startPage(pageNum, pageSize); 后来使用了多数据源(不同的数据库),Page ...

  6. springboot整合mybatis增删改查(四):完善增删改查及整合swgger2

    接下来就是完成增删改查的功能了,首先在config包下配置Druid数据连接池,在配置之前先把相关配置在application.preperties中完善 application.preperties ...

  7. SpringBoot整合MybatisPlus3.X之SQL执行分析插件(十四)

    pom.xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId& ...

  8. 5、SpringBoot+MyBaits+Maven+Idea+pagehelper分页插件

    1.为了我们平时方便开发,我们可以在同一个idea窗口创建多个项目模块,创建方式如下 2.项目中pom.xm文件的内容如下 <?xml version="1.0" encod ...

  9. springboot整合es客户端操作elasticsearch(四)

    对文档查询,在实际开发中,对文档的查询也是偏多的,记得之前在mou快递公司,做了一套事实的揽件数据操作,就是通过这个来存储数据的,由于一天的数据最少拥有3500万数据 所以是比较多的,而且还要求查询速 ...

随机推荐

  1. 基于Docker搭建大数据集群(一)Docker环境部署

    本篇文章是基于Docker搭建大数据集群系列的开篇之作 主要内容 docker搭建 docker部署CentOS 容器免密钥通信 容器保存成镜像 docker镜像发布 环境 Linux 7.6 一.D ...

  2. Nginx安装教程,ubuntu18.04

    本文介绍Nginx如何安装,操作系统为Ubuntu 18.04.   一.安装 (1)安装git 执行命令:“sudo apt-get install git”. (2)安装aptitude 执行命令 ...

  3. 利用sqlalchemy 查询视图

    这个问题 google 百度 中英文搜了一上午.最新的回答还是 7年前.最后自己靠着官方文档的自己改出来一个比较方便的方法 使用环境 python == 3.7.0 SQLAlchemy === 1. ...

  4. ps 将图片四角变成圆角

    1.用PS打开一张图片,用矩形选框工具,选出你要保留的的那一部分,“选择→修改→平滑”.在弹出的选框里添入数值,值越大角就越圆. 2.选择“选择→反选”,再按delete删除就ok了.

  5. FastDfs之StorageServer的详细配置介绍

    #这个配置文件是否失效 disabled=false #false为有效 true为无效 # 本storage server所属的group名 group_name=group1 # 可以版定一个ip ...

  6. 分库分表(2) --- ShardingSphere(理论)

    ShardingSphere---理论 ShardingSphere在中小企业需要分库分表的时候用的会比较多,因为它维护成本低,不需要额外增派人手;而且目前社区也还一直在开发和维护,还算是比较活跃. ...

  7. c++ 对特定进程的内存监控

    在工具实现的过程中,遇到了内存爆了的问题,部分模型的规模可以达到10的100次方方甚至1000次方.(工具的主要算法涉及到了递归,递归深度会很深,所以也用到了ulimit修改栈空间来缓解爆栈的问题,治 ...

  8. 配置VC++2010的glut库

    VC++2010是一个成熟稳定的版本,微软的编译工具Visual Studio系列从VC6到如今的VC2019,功能非常强大,我们在开始学习C++和计算机图形学的时候,一般入手<<C++P ...

  9. LeetCode 第 287 号问题:寻找重复数,一道非常简单的数组遍历题,加上四个条件后感觉无从下手

    今天分享的题目来源于 LeetCode 第 287 号问题:寻找重复数. 题目描述 给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个 ...

  10. VirtualBox for Mac 6.0.14 开源免费虚拟机方案

    VirtualBox for mac是一款开源虚拟机软件,你可以利用该软件在Mac OS平台上运行Windows软件,即可以在一定程度上弥补Mac OS平台软件不足的劣势,玩家也可以获得Windows ...