• MP简单的分页查询测试


    好久没水后端的东西了,最近在做vue项目写前端的代码,所以cloud也停进度了,吃完饭突然记得我没有在博客里写分页的东西,虽然项目中用到了,但是没有拎出来,这里就拎出来看看。


    导入最新的mp依赖是第一步不然太低的版本什么都做不了,3,1以下的好像连分页插件都没有加进去,所以我们用最新的3.5的,保证啥都有:

    1. <dependency>
    2. <groupId>com.baomidougroupId>
    3. <artifactId>mybatis-plus-boot-starterartifactId>
    4. <version>3.5.2version>
    5. dependency>

    这里我们需要认识两个插件:mp的核心插件MybatisPlusInterceptor与自动分页插件PaginationInnerInterceptor。

    MybatisPlusInterceptor的源码(去掉中间的处理代码):

    1. public class MybatisPlusInterceptor implements Interceptor {
    2. private List interceptors = new ArrayList();
    3. public MybatisPlusInterceptor() {}
    4. public Object intercept(Invocation invocation) throws Throwable {}
    5. public Object plugin(Object target) {}
    6. public void addInnerInterceptor(InnerInterceptor innerInterceptor) {}
    7. public List getInterceptors() {}
    8. public void setProperties(Properties properties) {}
    9. public void setInterceptors(final List interceptors) {}
    10. }

    我们可以发现它有一个私有的属性列表 List 而这个链表中的元素类型是InnerInterceptor。

    InnerInterceptor源码:

    1. public interface InnerInterceptor {
    2. default boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    3. return true;
    4. }
    5. default void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    6. }
    7. default boolean willDoUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
    8. return true;
    9. }
    10. default void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
    11. }
    12. default void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
    13. }
    14. default void beforeGetBoundSql(StatementHandler sh) {
    15. }
    16. default void setProperties(Properties properties) {
    17. }
    18. }

    不难发现这个接口的内容大致就是设置默认的属性,从代码的意思上就是提供默认的数据库操作执行时期前后执行的一些逻辑,谁实现它的方法会得到新的功能?

    再看看PaginationInnerInterceptor插件的源码:

    1. public class PaginationInnerInterceptor implements InnerInterceptor {
    2. protected static final List COUNT_SELECT_ITEM = Collections.singletonList((new SelectExpressionItem((new Column()).withColumnName("COUNT(*)"))).withAlias(new Alias("total")));
    3. protected static final Map countMsCache = new ConcurrentHashMap();
    4. protected final Log logger = LogFactory.getLog(this.getClass());
    5. protected boolean overflow;
    6. protected Long maxLimit;
    7. private DbType dbType;
    8. private IDialect dialect;
    9. protected boolean optimizeJoin = true;
    10. public PaginationInnerInterceptor(DbType dbType) {
    11. this.dbType = dbType;
    12. }
    13. public PaginationInnerInterceptor(IDialect dialect) {
    14. this.dialect = dialect;
    15. }
    16. public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    17. IPage page = (IPage)ParameterUtils.findPage(parameter).orElse((Object)null);
    18. if (page != null && page.getSize() >= 0L && page.searchCount()) {
    19. MappedStatement countMs = this.buildCountMappedStatement(ms, page.countId());
    20. BoundSql countSql;
    21. if (countMs != null) {
    22. countSql = countMs.getBoundSql(parameter);
    23. } else {
    24. countMs = this.buildAutoCountMappedStatement(ms);
    25. String countSqlStr = this.autoCountSql(page, boundSql.getSql());
    26. MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
    27. countSql = new BoundSql(countMs.getConfiguration(), countSqlStr, mpBoundSql.parameterMappings(), parameter);
    28. PluginUtils.setAdditionalParameter(countSql, mpBoundSql.additionalParameters());
    29. }
    30. CacheKey cacheKey = executor.createCacheKey(countMs, parameter, rowBounds, countSql);
    31. List result = executor.query(countMs, parameter, rowBounds, resultHandler, cacheKey, countSql);
    32. long total = 0L;
    33. if (CollectionUtils.isNotEmpty(result)) {
    34. Object o = result.get(0);
    35. if (o != null) {
    36. total = Long.parseLong(o.toString());
    37. }
    38. }
    39. page.setTotal(total);
    40. return this.continuePage(page);
    41. } else {
    42. return true;
    43. }
    44. }
    45. public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {...........省略之后全部的内容........}
    46. 我们不难发现它实现了来自于InnerInterceptor的方法,这里面的源码有时间需要好好处处逻辑。

      我们知道了分页插件和核心插件的关系,也就是我们可以将分页插件添加入核心插件内部的插件链表中去,从而实现多功能插件的使用。


      配置mp插件,并将插件交由spring管理(我们用的是springboot进行测试所以不需要使用xml文件):

      1. import com.baomidou.mybatisplus.annotation.DbType;
      2. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
      3. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
      4. import org.springframework.context.annotation.Bean;
      5. import org.springframework.context.annotation.Configuration;
      6. @Configuration
      7. public class MpConfig {
      8. /*分页插件的配置*/
      9. @Bean
      10. public MybatisPlusInterceptor mybatisPlusInterceptor() {
      11. /*创建mp拦截器*/
      12. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
      13. /*创建分页插件*/
      14. PaginationInnerInterceptor pagInterceptor = new PaginationInnerInterceptor();
      15. /*设置请求的页面大于最大页容量后的请求操作,true回调第一页,false继续翻页,默认翻页*/
      16. pagInterceptor.setOverflow(false);
      17. /*设置单页分页的条数限制*/
      18. pagInterceptor.setMaxLimit(500L);
      19. /*设置数据库类型*/
      20. pagInterceptor.setDbType(DbType.MYSQL);
      21. /*将分页拦截器添加到mp拦截器中*/
      22. interceptor.addInnerInterceptor(pagInterceptor);
      23. return interceptor;
      24. }
      25. }

      配置完之后写一个Mapper接口:

      1. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
      2. import com.hlc.mp.entity.Product;
      3. import org.apache.ibatis.annotations.Mapper;
      4. @Mapper
      5. public interface ProductMapper extends BaseMapper {
      6. }

      为接口创建一个服务类(一定按照mp编码的风格来):

      1. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
      2. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
      3. import com.baomidou.mybatisplus.extension.service.IService;
      4. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
      5. import com.hlc.mp.entity.Product;
      6. import com.hlc.mp.mapper.ProductMapper;
      7. import org.springframework.beans.factory.annotation.Autowired;
      8. import org.springframework.stereotype.Service;
      9. import java.util.List;
      10. @Service(value = "ProductService")
      11. public class ProductServiceImpl extends ServiceImpl
      12. implements IService {
      13. @Autowired
      14. ProductMapper productMapper;
      15. /**
      16. * 根据传入的页码进行翻页
      17. *
      18. * @param current 当前页码(已经约定每页数据量是1条)
      19. * @return 分页对象
      20. */
      21. public Page page(Long current) {
      22. /*current首页位置,写1就是第一页,没有0页之说,size每页显示的数据量*/
      23. Page productPage = new Page<>(current, 1);
      24. /*条件查询分页*/
      25. QueryWrapper queryWrapper = new QueryWrapper<>();
      26. queryWrapper.eq("status", 0);
      27. productMapper.selectPage(productPage, queryWrapper);
      28. return productPage;
      29. }
      30. }

      到这里我们可以看到分页的具体方法就是,先创建一个分页对象,规定页码和每一页的数据量的大小,其次确定查询操作的范围,并使用BaseMapper给予我们的查询分页方法selectPage(E page,Wapper queryWapper)进行查询分页的操作。


      测试类:

      1. @Test
      2. public void testPage(){
      3. IPage productIPage = productService.page(2L);
      4. productIPage.getRecords().forEach(System.out::println);
      5. System.out.println("当前页码"+productIPage.getCurrent());
      6. System.out.println("每页显示数量"+productIPage.getSize());
      7. System.out.println("总页数"+productIPage.getPages());
      8. System.out.println("数据总量"+productIPage.getTotal());
      9. }

      运行查看分页结果:

       我们可以发现都正常的按照我们传入的页码去查询对应的页数据了,因为我设置的每页只展示一条数据,所以ID如果对应页码就说明分页成功。

    47. 相关阅读:
      2022年8月总结
      markdown语法大全_Markdown超详细介绍
      Android Studio 导入自己编译的 framework.jar
      51.HarmonyOS鸿蒙系统 App(ArkUI)通知
      python查找与排序算法详解(示意图+代码、看完基础不成问题)
      java计算机毕业设计口红专卖网站源码+mysql数据库+系统+lw文档+部署
      禅道:提bug、管理case 7.0
      sqli-labs less9详解
      基于行为透明性的RPKI撤销检测机制
      【初学者入门C语言】之习题篇(二)
    48. 原文地址:https://blog.csdn.net/m0_59588838/article/details/127787264