Mybatis-PageHelper分页插件的使用与相关原理分析

前言

今天使用了分页插件,并将其整合到SpringBoot中。各种遇到了个别问题,现在记录下。吃一垫长一智。

整合

与SpringBoot整合

1. 引入依赖

   <!--pagehelper 分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

2. 配置参数

接着在application.yml中配置相关参数

#pagehelper
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
    returnPageInfo: check

参数说明
https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

3.使用

  #方式1
  PageHelper.startPage(1, 10);
   List<ScoreGoodsCategory> goodsCategoryList = mapper.selectByPage();
   int totalCount=(int) ((Page)goodsCategoryList).getTotal();
   # 方式二
   PageHelper.offsetPage(1, 10);
   List<ScoreGoodsCategory> goodsCategoryList = mapper.selectByPage();
   PageInfo<ScoreGoodsCategory> pageInfo = new PageInfo<>(goodsCategoryList);
   int totalCount=(int) pageInfo.getTotal();

与Spring MVC 整合

1. 引入依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>最新版本</version>
</dependency>

2. 配置拦截器(这是核心,如果不配置则分页不起作用)

在Spring的配置文件中配置拦截器插件

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <!-- 注意其他配置 -->
  <property name="plugins">
    <array>
      <bean class="com.github.pagehelper.PageInterceptor">
        <property name="properties">
          <!--使用下面的方式配置参数,一行配置一个 -->
          <value>
            params=count=countSql
          </value>
		   <value>
            helperDialect=mysql
          </value>
		   <value>
            reasonable=true
          </value>
		    <value>
            supportMethodsArguments=true
          </value>
		     <value>
            returnPageInfo=check
          </value>
        </property>
      </bean>
    </array>
  </property>
</bean>

配置好之后,使用同上。

原理

其最核心的方法就在拦截器中,那我们首先看看拦截器中的拦截方法。该方法主要做了两件事,1. 统计总条数,2.对原始的SQL进行改写使其可以分页。
PageInterceptor类的intercept方法是拦截器的总入口方法。

1.统计总条数

首先,我们来看看统计总条数的相关代码。

//PageInterceptor 类
//设置count的sql的id,在原始的msId后面加上_COUNT后缀。
 String countMsId = msId + countSuffix;
 // 生成统计sql的入口方法
 count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler);

接下来我们就来看看executeAutoCount 方法

  /**
     * 执行自动生成的 count 查询
     *
     * @param executor sql执行器
     * @param countMs
     * @param parameter
     * @param boundSql 
     * @param rowBounds  
     * @param resultHandler  结果处理器
     * @return
     * @throws IllegalAccessException
     * @throws SQLException
     */
    private Long executeAutoCount(Executor executor, MappedStatement countMs,
                                   Object parameter, BoundSql boundSql,
                                   RowBounds rowBounds, ResultHandler resultHandler) throws IllegalAccessException, SQLException {
        Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
        //创建 count 查询的缓存 key
        CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql);
        //调用方言获取 count sql
        String countSql = dialect.getCountSql(countMs, boundSql, parameter, rowBounds, countKey);
        //countKey.update(countSql);
        BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql, boundSql.getParameterMappings(), parameter);
        //当使用动态 SQL 时,可能会产生临时的参数,这些参数需要手动设置到新的 BoundSql 中
        for (String key : additionalParameters.keySet()) {
            countBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
        }
        //执行 count 查询
        Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql);
        Long count = (Long) ((List) countResultList).get(0);
        return count;
    }

如上,方法的注释比较详实,此处我们主要介绍下第二步调用方言获取 count sql。dialect 是一个接口类,PageHelper是其的一个实现类。接着我们来看看PageHelper中的getCountSql方法。

。。。。。。。。。。。。。。。。。


版权原因,完整文章,请参考如下:

Mybatis-PageHelper分页插件的使用与相关原理分析

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Mybatis-Plus分页插件是一个基于Mybatis分页插件,可以方便地实现分页查询功能。使用该插件,只需要在Mapper接口中定义一个继承BaseMapper的接口,并在方法中使用Page对象进行分页查询即可。 具体使用步骤如下: 1. 引入Mybatis-Plus分页插件依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> ``` 2. 定义Mapper接口 在Mapper接口中继承BaseMapper,并定义一个方法,使用Page对象进行分页查询。例如: ``` public interface UserMapper extends BaseMapper<User> { List<User> selectUserPage(Page<User> page, @Param("name") String name); } ``` 3. 在Service中调用Mapper方法 在Service中调用Mapper方法,传入Page对象和查询条件,例如: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public IPage<User> getUserPage(Page<User> page, String name) { return userMapper.selectUserPage(page, name); } } ``` 4. 在Controller中调用Service方法 在Controller中调用Service方法,传入Page对象和查询条件,例如: ``` @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/page") public IPage<User> getUserPage(Page<User> page, String name) { return userService.getUserPage(page, name); } } ``` 以上就是Mybatis-Plus分页插件使用步骤。通过使用该插件,可以方便地实现分页查询功能,提高开发效率。 ### 回答2: Mybatis-Plus是一个基于Mybatis的增强工具,为了提高开发效率和减少重复的CRUD操作而生。其中,Mybatis-Plus分页插件是其重要的功能之一,可以帮助开发人员快速的实现数据的分页查询。 Mybatis-Plus分页插件使用非常简单,开发人员只需要在Mybatis-Plus的配置文件中进行一些简单的配置即可。以下是为您提供的Mybatis-Plus分页插件使用方法: 1.引入依赖:首先我们需要在项目中引入自己构建的mybatis-plus-boot-starter,或者直接在pom.xml中引入Mybatis-Plus对应版本的依赖。 2.配置分页插件:在mybatis-plus.yml中配置分页插件,如下所示: mybatis-plus: # 配置分页插件 configuration: map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 配置 Mybatis-Plus 分页插件 plugins: - interceptor: class: com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor 3.配置分页查询:在Mapper接口方法中添加分页参数,在Mapper.xml文件中添加分页查询的具体SQL语句,如下所示: //mapper 接口 public interface YourMapper extends BaseMapper<YourEntity> { IPage<YourEntity> selectPageVo(Page page, @Param("yourEntity") YourEntity yourEntity); } <!-- Mapper.xml --> <select id="selectPageVo" resultType="YourEntityVo"> select {yourEntity.*} from your_entity {yourEntity} where 1=1 <if test="yourEntity.name != null and yourEntity.name!=''"> and yourEntity.name like '%${yourEntity.name}%' </if> </select> 4.使用分页查询:在Service层中使用分页查询,如下所示: @Override public IPage<YourEntity> selectPageVo(Page<YourEntity> page, YourEntity yourEntity) { return this.getBaseMapper().selectPageVo(page, yourEntity); } 使用Mybatis-Plus分页插件,不仅可以实现简单的分页查询,而且还可以自定义查询条件、排序方式等。总之,这是一个非常方便和实用的插件,可以让开发人员更快地进行数据操作和维护。 ### 回答3: Mybatis-plus 是一款基于 Mybatis 的增强工具包,它提供了很多的快捷操作,其中就包括分页插件使用 Mybatis-plus 分页插件可以简化分页操作,提高代码的可读性和可维护性。 使用分页插件,需要先引入 Mybatis-plus 的依赖包。在 Spring Boot 中,可以通过 Gradle 或 Maven 的方式引入 Mybatis-plus 相关依赖,例如: ``` groovy dependencies { implementation 'com.baomidou:mybatis-plus-boot-starter:3.4.2' } ``` 在配置文件中加入分页插件配置: ``` yml mybatis-plus: page-params: limit: 10 # 每页显示条数 max-limit: 100 # 最大显示条数 overflow: false # 是否溢出 ``` 其中,`limit` 表示每页显示的条数,`max-limit` 表示最大显示的条数,`overflow` 表示是否允许溢出。 在 Mybatis-plus 的 Mapper 接口中定义查询方法时,需要加入 `IPage` 类型的参数,例如: ``` java import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; public interface UserMapper extends BaseMapper<User> { IPage<User> selectPageVo(Page<?> page, UserVo userVo); } ``` 其中,`Page` 类是 Mybatis-plus 中提供的分页对象,`User` 是实体类,`UserVo` 是查询参数,`selectPageVo` 方法就是查询分页方法。 在 Service 层中调用 Mapper 中定义的分页方法: ``` java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public IPage<User> selectPageVo(UserVo userVo) { Page<User> page = new Page<>(); page.setCurrent(userVo.getCurrentPage()); page.setSize(userVo.getPageSize()); return baseMapper.selectPageVo(page, userVo); } } ``` 在上面的示例中,`Page` 对象中设置了分页参数,`baseMapper` 是继承自 `BaseServiceImpl` 的默认的 Mapper 对象,`selectPageVo` 方法返回分页查询结果。 最后,在 Controller 中调用 Service 方法: ``` java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/page") public IPage<User> selectPageVo(UserVo userVo) { return userService.selectPageVo(userVo); } } ``` 在上面的示例中,`selectPageVo` 方法返回的就是分页查询结果。在前端展示时,可以通过获取到的 `IPage` 对象获取分页信息和查询结果,例如: ```javascript axios.get('/users/page', { params: { currentPage: 1, pageSize: 10, username: 'Tom' } }).then(res => { // 获取分页信息和查询结果 const { current, total, records } = res.data; // ... }); ``` 通过 Mybatis-plus 的分页插件,我们不仅可以简化分页操作,还可以通过配置实现一些高级功能,例如性能优化和多租户分页。因此,Mybatis-plus 的分页插件是一个非常实用的工具,值得推荐使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值