springboot集成Mybatis的分页工具PageHelper

前言: 对于列表查询,往往用到分页,手写分页工具相对麻烦,而且bug较多,所以找来Mybatis官方提供的分页工具,并记录一下学习过程。

前提是项目中已经配置了MyBatis
使用步骤
  • maven配置
<!-- 分页器配置 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
  • 初始化配置(有两种方式,二选一就行)
  1. 配置文件配置 yml
# 分页配置
pagehelper:
  offset-as-page-num: true
  row-bounds-with-count: true
  page-size-zero: true
  reasonable: false
  helper-dialect: mysql
  support-methods-arguments: true
  params: count=countSql
  1. 配置文件配置

import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * mybatis分页插件配置
 */
@Configuration
public class MyBatisConfig {
    @Bean
    public PageHelper pageHelper(){
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();

        // 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用
        p.setProperty("offsetAsPageNum","true");

        //设置为true时,使用RowBounds分页会进行count查询
        p.setProperty("rowBoundsWithCount","true");
        p.setProperty("reasonable","true");
        pageHelper.setProperties(p);
        return pageHelper;
    }
}
  • mapper
 	@Select("SELECT * FROM lhw_articles")
    List<LhwArticles> getAllArticle();
  • Service
List<LhwArticles> getAllArticle();
  • ServiceImpl
    @Override
    public List<LhwArticles> getAllArticle() {
        return articleMapper.getAllArticle();
    }
  • Controller层调用
    @RequestMapping(path = "/all", method = RequestMethod.GET)
    public JsonBuilder getAllArticle(@RequestParam(value = "page", defaultValue = "1") int page,
                                     @RequestParam(value = "size", defaultValue = "10") int size){
        PageHelper.startPage(page, size);
        List<LhwArticles> allArticle = articleService.getAllArticle();
        Map<String, Object> map = pageUtils.dealPageInfo(allArticle, page);
        return JsonBuilder.buildSuccess(map);
    }

PageHelper.startPage调用后,会对它后面第一条执行的sql进行拼接,形成分页处理。

注意事项
  1. 使用PageHelper.startPage进行分页时, mapper中的sql语句末尾不能加 分号,否则会报sql语法错误。
  • 正确形式:
	@Select("SELECT * FROM lhw_articles")
    List<LhwArticles> getAllArticle();
  • 错误形式
 	@Select("SELECT * FROM lhw_articles;")
    List<LhwArticles> getAllArticle();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITzhongzi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值