zoukankan      html  css  js  c++  java
  • SpringBoot集成Mybatis-PageHelper分页工具类,实现3步完成分页

    在Mybatis中,如果想实现分页是比较麻烦的,首先需要先查询出总的条数,然后再修改mapper.xml,为sql添加limit指令。

    幸运的是现在已经不需要这么麻烦了,刘大牛实现了一个超牛的分页工具类(https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md)

    到底有多牛呢?现在一个分页实现只需要2步,像下面这样:

    PageHelper.startPage(pageNum, pageSize);
    List<Bean> list = mapper.selectByExample(example);
    return new PageInfo<>(list);

    是不是跃跃欲试了?let's begin!

    maven依赖

    <!--mybatis-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.1</version>
    </dependency>
    <!--mapper-->
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>1.1.4</version>
    </dependency>
    <!--pagehelper-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.1</version>
    </dependency>

    在src/main/resources中需要创建META-INF文件夹,其中存放spring-devtools.properties文件,具体内容如下:

    restart.include.mapper=/mapper-[\w-\.]+jar
    restart.include.pagehelper=/pagehelper-[\w-\.]+jar

    application.yml配置信息

    #mybatis
    mybatis:
    #指定领域类的路径
      typeAliasesPackage: com.cky.domain
    #指定mapper.xml的路径
      mapperLocations: classpath:mapper/*.xml
    
    mapper: 
      mappers:
    #此处填写需要分页的Mapper的全路径类名。例如com.cky.xxxMapper
      - xxxxx
      - xxxxx
      not-empty: false
      identity: MYSQL
    
    pagehelper:
        helperDialect: mysql
        reasonable: true
        supportMethodsArguments: true
        params: count=countSql

    在Application添加@MapperScan("com.cky.mapper")指定mapper的路径

    使用:

    在任意的Mapper查询方法前后分别添加如下两句:需要注意的是PageHelper必须紧挨着Mapper查询方法才能使PageHelper生效,当我们把list放入PageInfo 中时,他会自动计算分页所需要的信息。

    PageHelper.startPage(pageNum, pageSize);
    List<Bean> list = mapper.selectByExample(example);
    return new PageInfo<>(list);

    本实例只讲了springboot的集成,像spring的集成可以查看上面提供的github网址,其中的教程也十分好,中文的哦!

  • 相关阅读:
    对象池使用时要注意几点
    Flash3D学习计划(一)——3D渲染的一般管线流程
    714. Best Time to Buy and Sell Stock with Transaction Fee
    712. Minimum ASCII Delete Sum for Two Strings
    647. Palindromic Substrings(马拉车算法)
    413. Arithmetic Slices
    877. Stone Game
    338. Counting Bits
    303. Range Sum Query
    198. House Robber
  • 原文地址:https://www.cnblogs.com/chenkeyu/p/8512978.html
Copyright © 2011-2022 走看看