Mybatis分页插件PageHelper使用

客官°小女子只卖身不卖艺 2022-04-10 03:42 546阅读 0赞

目录

        • SSM项目中使用
        • SpringBoot项目中使用

SSM项目中使用

  1. 导入依赖


    com.github.pagehelper
    pagehelper
    4.1.6
  2. 配置分页插件

配置分页插件有两种方式:

1). 在 mybatis-config.xml 中使用

  1. <plugins>
  2. <!--分页-->
  3. <plugin interceptor="com.github.pagehelper.PageHelper">
  4. <!-- 告诉分页插件是哪个数据库, Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
  5. <property name="dialect" value="mysql"/>
  6. </plugin>
  7. </plugins>

在 spring-dao.xml 中读取 mybatis-config.xml 配置文件

  1. <!--sqlSessionFactory-->
  2. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  3. <!-- 注入数据源 -->
  4. <property name="dataSource" ref="dataSource"/>
  5. <!-- 配置MyBaties全局配置文件 -->
  6. <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"/>
  7. <!-- 扫描mapper文件 -->
  8. <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
  9. <!-- 扫描实体类 使用别名 -->
  10. <property name="typeAliasesPackage" value="com.learn.pojo"/>
  11. </bean>

2). 在 spring-dao.xml 中使用

  1. <!--sqlSessionFactory-->
  2. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  3. <!-- 注入数据源 -->
  4. <property name="dataSource" ref="dataSource"/>
  5. <!-- 配置MyBaties全局配置文件 -->
  6. <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"/>
  7. <!-- 扫描mapper文件 -->
  8. <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
  9. <!-- 扫描实体类 使用别名 -->
  10. <property name="typeAliasesPackage" value="com.learn.pojo"/>
  11. <!--配置分页插件-->
  12. <property name="plugins">
  13. <array>
  14. <bean class="com.github.pagehelper.PageHelper">
  15. <property name="properties">
  16. <!-- config params as the following -->
  17. <value>
  18. dialect=mysql
  19. </value>
  20. </property>
  21. </bean>
  22. </array>
  23. </property>
  24. </bean>

注:如果导入的依赖版本为 5.0 以上,插件须改成 com.github.pagehelper.PageInterceptor

  1. 使用 PageHelper

    PageHelper.startPage(pageNum, pageSize);
    // 查询
    List shopList = shopMapper.queryShopList(shopCondition);
    PageInfo pageInfo = new PageInfo<>(shopList);

分页信息都已保存在 pageInfo 对象中,可以按自己的需求从pageInfo中取出对应的信息返回给前台

SpringBoot项目中使用

  1. 导入依赖


    com.github.pagehelper
    pagehelper-spring-boot-starter
    1.2.7
  2. 在 application.yml 配置 pagehelper

    分页插件

    pagehelper:

    1. helper-dialect: mysql
  3. 使用 PageHelper

    Page page = PageHelper.startPage(pageNum, pageSize, true);
    // 查询
    List roles = this.roleMapper.listAll(role);
    PageInfo pageInfo = new PageInfo<>(roles);

注:PageInfo pageInfo = new PageInfo<>(roles) 这行代码可以省略,分页的基本信息都已保存在 page 对象中,可以自己自定义一个VO,通过page.get…()方法取出,然后把自定义VO返回。
20181224163352121.png
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,546人围观)

还没有评论,来说两句吧...

相关阅读

    相关 mybatisPageHelper

        最近有个小项目,不和旧系统有关系,所以简单搭建了一个SSM框架。在项目进行中,遇到需要分页显示数据的需求,记得之前接触mybatis框架用的就是插件,很方便,所以这次