Mybatis 分页

一、Mybatis Plus 分页

1. 配置

创建MybatisPlusConfig配置类,配置分页插件

package com.example.pagetest.conf;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MybatisPlus配置类
 */
@Configuration
public class MyBatisPlusConfig {

    /**
     * MybatisPlus拦截器添加分页插件
     *
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}
2. 纯代码分页查询
(1) 执行查询(这里调用的是IService接口的page方法,也可以使用BaseMapper接口的selectPage方法)
    @GetMapping("/list/page")
    public Page listPage(Integer sex, Long pageCurrent, Long pageSize) {
        log.info("current: {}, pageSize: {}", pageCurrent, pageSize);
        // 构造查询条件
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sex", sex);
        // 创建分页对象
        Page page = new Page<>(pageCurrent, pageSize);
        // 调用IService接口的page方法,执行分页查询
        Page userPage = userService.page(page, queryWrapper);
        return userPage;
    }
(2) 返回结果

{

    "records": [

        {

            "id": 1,

            "name": "张三",

            "age": 18,

            "sex": 0,

            "createTime": null,

            "createBy": null

        },

        {

            "id": 2,

            "name": "李四",

            "age": 19,

            "sex": 0,

            "createTime": null,

            "createBy": null

        }

    ],

    "total": 4,

    "size": 2,

    "current": 1,

    "orders": [],

    "optimizeCountSql": true,

    "searchCount": true,

    "countId": null,

    "maxLimit": null,

    "pages": 2

}

3. 自定义sql分页

(1)mapper接口

@Mapper
public interface UserMapper extends BaseMapper {
    Page selectListPage(Page page, @Param("sex") Integer sex);
}

(2)自定义SQL

    

(3)代码

    @Override
    public Page queryListPageBySQl(Integer sex, Long pageCurrent, Long pageSize) {
        // 创建分页对象
        Page page = new Page<>(pageCurrent, pageSize);
        Page userPage = userMapper.selectListPage(page, sex);
        return userPage;
    }

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