• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Y-wee
博客园    首页    新随笔    联系   管理     

Mybatis-Plus 分页插件

Mybatis-Plus 分页插件

Mybatis-Plus分页插件的简单使用

配置分页插件对象

package com.yl.mybatis.plus.guigu.config;

import com.baomidou.mybatisplus.annotation.DbType;
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;

/**
 * mybatispuls配置类
 *
 * @author Y-wee
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 将MybatisPlusInterceptor交给容器管理
     *
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //设置数据库类型
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        return interceptor;
    }

}

测试分页功能

@Test
public void testPage(){
    // 创建分页对象并设置页码和页大小
    Page<User> page = new Page<>(1,3);
    // SELECT id,name,age,email FROM user LIMIT ?(当页码=1时可以省略)
    mapper.selectPage(page, null);
    // 获取分页数据(返回的Page == 入参的Page)
    List<User> userList = page.getRecords();
    userList.forEach(System.out::println);
}

自定义mapper方法使用分页插件

mapper

package com.yl.mybatis.plus.guigu.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yl.mybatis.plus.guigu.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

/**
 * 用户
 *
 * @author Y-wee
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

    /**
     * 分页
     *
     * @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位
     * @param age
     * @return
     */
    Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.yl.mybatis.plus.guigu.mapper.UserMapper">
    <sql id="tableName">`user`</sql>

    <!--分页-->
    <select id="selectPageVo" resultType="User">
        select * from <include refid="tableName"/> where age>#{age}
    </select>
</mapper>

测试

@Test
public void testPage(){
    Page<User> page = new Page<>(2,3);
    // select * from `user` where age>? LIMIT ?,?
    mapper.selectPageVo(page, 20);

    List<User> userList = page.getRecords();
    userList.forEach(System.out::println);
}

官方文档:https://baomidou.com/pages/97710a/#自定义的-mapper-method-使用分页

记得快乐
posted @ 2020-10-29 20:31  Y-wee  阅读(933)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3