MyBatis分页

MyBatis 分页

版本:springboot-2.x/pagehelper-spring-boot-starter-1.4.3/mysql

步骤

1.引入依赖

org.mybatis.spring.boot.mybatis-spring-boot-starter 2.2.2
com.github.pagehelper.pagehelper-spring-boot-starter 1.4.3

2.配置 Mybatis-PageHelper

这一步是使用 Mybatis-PageHelper必须配置的,否则结果集的 list 总是为空

page-helper.helperDialect.reasonable: true
page-helper.helperDialect.supportMethodsArguments=true
page-helper.helperDialect.params=count=countSql

3.代码

User

@Data
public class User {
​
    Integer pageNum;
    Integer pageSize;
    
    private Long uid;
    private String uname;
    // ...
}

Controller:POST

    @RequestMapping(value="/listAllUser", method= RequestMethod.POST)
    public Result<?> listAllUser(@RequestBody User user) {
        PageInfo<User> userPageInfo = loginService.listAllUser(user);
        return Result.success(userPageInfo);
    }

ServiceImpl

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
​
    @Override
    public PageInfo<User> listAllUser(User user) {
        // 执行前一句PageHelper.startPage()
        PageHelper.startPage(user.getPageNum(), user.getPageSize());
        List<User> users = userMapper.selectUserList(user);
        // 执行后new成PageInfo对象
        return new PageInfo<>(users);
    }

这里的步骤是关键。

结果:分页查询的话后台每次会默认另外跑一条 sql 语句专门去查询总条数。

SELECT count(0) FROM t_user

Mapper

    List<User> selectUserList(User User);

mapper.xml:常规的查询方法

    <resultMap type="com.jtt.domain.User" id="UserResult">
        <result property="uid"    column="uid"    />
        <result property="uname"    column="uname"    />
        <result property="upwd"    column="upwd"    />
        <result property="pwdErr"    column="pwd_err"    />
    </resultMap>
​
    <sql id="selectUserVo">
        select uid, uname, upwd, pwd_err from t_user
    </sql>
​
    <select id="selectUserList" parameterType="com.jtt.domain.User" resultMap="UserResult">
        <include refid="selectUserVo"/>
        <where>  
            <if test="uname != null  and uname != ''"> and uname like concat('%', #{uname}, '%')</if>
            <if test="upwd != null  and upwd != ''"> and upwd = #{upwd}</if>
            <if test="pwdErr != null "> and pwd_err = #{pwdErr}</if>
        </where>
    </select>

4.验证

postman中选择请求方式和路径,打开 Body - raw - 右方下拉选择 JSON 格式(*) - 拷贝下方请求参数 - 确认发送请求

{
    "pageNum": 2,
    "pageSize": 5
}

5.结果

[2022-08-14 19:35:00] 日志

{
    "code": 200,
    "message": "成功",
    "data": {
        "total": 12,
        "list": [
            {
                "uid": 6,
                "uname": "452345",
                "upwd": "password",
                "pwdErr": 4
            },
            {
                "uid": 7,
                "uname": "523",
                "upwd": "password",
                "pwdErr": 5
            },
            {
                "uid": 8,
                "uname": "453",
                "upwd": "password",
                "pwdErr": 1
            },
            {
                "uid": 9,
                "uname": "234523",
                "upwd": "password",
                "pwdErr": 3
            },
            {
                "uid": 10,
                "uname": "45",
                "upwd": "password",
                "pwdErr": 3
            }
        ],
        "pageNum": 2,
        "pageSize": 5,
        "size": 5,
        "startRow": 6,
        "endRow": 10,
        "pages": 3,
        "prePage": 1,
        "nextPage": 3,
        "isFirstPage": false,
        "isLastPage": false,
        "hasPreviousPage": true,
        "hasNextPage": true,
        "navigatePages": 8,
        "navigatepageNums": [
            1,
            2,
            3
        ],
        "navigateFirstPage": 1,
        "navigateLastPage": 3
    }
}

修改分页参数验证下一页数据。

其它可能出现的问题

(1)myabtis分页执行时只有一条count(0),结果集中total正确但是 list 为空:看看你是不是跳过了 applicationb.yml 里对分页插件的配置

(2)mybatis-log 插件不打印执行的 sql 语句

application.properties

logging.level.com.jtt.mapper=debug

∵ 日志打印是分级别的,日志总是打印当前级别及当前级别以下的日志内容。mybatis的日志级别是 debug,springboot的默认级别是 info,排在 debug 后面,所以总是打印不出来 mybatis 的日志。

解决方法:重写 springboot 的日志级别为 debuglogging.level后面可以跟包名或者类的全路径名指定哪个包或者那个类的日志级别,如这里配置的就是 com.jtt.mapper 包以下的类统一升到 debug 上去。

附录

配置参数的说明:

  • page-helper.reasonable 必填 经实验,该条是分页唯一必配的参数,否则查询返回 list 数据部分为[]

  • page-helper.supportMethodsArguments 支持方法参数

//第四种,参数方法调用
//存在以下 Mapper 接口方法,你不需要在 xml 处理后两个参数
public interface CountryMapper {
    List<User> selectByPageNumSize(
            @Param("user") User user,
            @Param("pageNum") int pageNum, 
            @Param("pageSize") int pageSize);
}
//配置supportMethodsArguments=true
//在代码中直接调用:
List<User> list = userMapper.selectByPageNumSize(user, 1, 10);

相当于 JPA 在自带的无参方法 findAll() 里放一个 Pageable 进去使其变成分页查询。

  • page-helper.params 一些默认的参数,可以通过键对值重写自定义对应的变量名,像你不想要默认的 pageNum,想换 myPageNum 作为页码,就可以配置 pagehelper.params=pageNum=myPageNum 重写。结果参数映射用自定义的参数请求和接受也没问题。

其它参数配置详见附录的参考资料

Mybatis-PageHelper/HowToUse.md at master · pagehelper/Mybatis-PageHelper (github.com)

参考资料:

Spring Boot入门系列(十六)整合pagehelper,一秒实现分页功能! - 腾讯云开发者社区-腾讯云 (tencent.com)

2.pageHelper的使用以及原理哔哩哔哩bilibili

Mybatis-PageHelper/HowToUse.md at master · pagehelper/Mybatis-PageHelper (github.com)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值