使用pagehelper 实现 mybatis 分页查询

通过 pagehelper实现 mybatis 分页查询

    • 1. 添加依赖:
    • 2. 配置PageHelper:
    • 3.在代码中使用PageHelper:
    • 4. 获取更多分页信息:

1. 添加依赖:

首先,你需要在项目的pom.xml文件中添加PageHelper的依赖。具体如下:

<dependency>
    <groupId>com.github.pagehelpergroupId>
    <artifactId>pagehelperartifactId>
    <version>5.1.2version> 
dependency>

2. 配置PageHelper:

方式一: Mybatis的配置文件(例如mybatis-config.xml)中配置PageHelper插件。具体如下:

<configuration>
    ...
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            
            <property name="dialect" value="mysql"/>
            <property name="reasonable" value="true"/>
            <property name="supportMethodsArguments" value="true"/>
            <property name="params" value="count=countSql"/>
        plugin>
    plugins>
    ...
configuration>

方式二: 在Spring Boot中使用Mybatis。在这种情况下,你可以通过在application.properties或application.yml文件中添加配置来配置PageHelper。

  • 在application.properties文件中配置PageHelper的示例:

    pagehelper.helperDialect=mysql
    pagehelper.reasonable=true
    pagehelper.supportMethodsArguments=true
    pagehelper.params=count=countSql
    
    
  • 如果你的项目中使用的是application.yml文件,配置PageHelper的示例如下:

    pagehelper:
      helperDialect: mysql
      reasonable: true
      supportMethodsArguments: true
      params: count=countSql
    
    

在Spring Boot项目中,你还需要添加Mybatis的启动器依赖,示例如下:

<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.1.4version> 
dependency>

记住,在Spring Boot中配置PageHelper的属性时,如果配置名称中包含大写字母,那么在application.properties或application.yml文件中,你应该使用小写字母并使用连字符(-)替换大写字母。例如,supportMethodsArguments应写为support-methods-arguments。

3.在代码中使用PageHelper:

使用PageHelper进行分页非常简单。在查询之前,只需要调用PageHelper的startPage方法即可。具体如下:

PageHelper.startPage(1, 10); // 第一个参数是页数,第二个参数是每页的大小
List<User> users = userMapper.selectByExample(new UserExample());

这样,返回的users列表就是分页查询的结果。注意,startPage方法只对紧随其后的第一个查询语句起作用,也就是说这个方法是基于ThreadLocal的。

4. 获取更多分页信息:

如果你还需要获取如总页数、总记录数等更多的分页信息,你可以将查询结果转化为PageInfo对象。具体如下:

PageHelper.startPage(1, 10);
List<User> users = userMapper.selectByExample(new UserExample());
PageInfo<User> pageInfo = new PageInfo<>(users);

然后,你可以通过PageInfo对象获取更多的分页信息,例如:

long total = pageInfo.getTotal(); // 获取总记录数
int pages = pageInfo.getPages(); // 获取总页数
List<User> list = pageInfo.getList(); // 获取当前页的数据

这就是PageHelper的基本使用方法。注意,PageHelper的分页查询是基于物理分页的,也就是说,查询结果是直接从数据库中提取的,而不是从内存中过滤的。

你可能感兴趣的:(mybatis,MySql,Spring,Boot,mybatis,spring,boot,java)