MybatisPlus使用分页功能

MybatisPlus 使用分页功能

分页查询是一个很常见的需求,故Mybatis-Plus提供了一个分页插件,使用它可以十分方便的完成分页查询。下面介绍Mybatis-Plus分页插件的用法,详细信息可参考[官方文档](分页插件 | MyBatis-Plus (baomidou.com))

首先为分页编写一个配置类:

@Configuration
public class MPConfiguration {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

分页插件使用说明

  1. 构造分页对象

分页对象包含了分页的各项信息,其核心属性如下:

属性名 类型 默认值 描述
records List emptyList 查询数据列表
total Long 0 查询列表总记录数
size Long 10 每页显示条数,默认10
current Long 1 当前页

分页对象既作为分页查询的参数,也作为分页查询的返回结果,当作为查询参数时,通常只需提供currentsize属性,如下:

IPage<T> page = new Page<>(current, size);

注:IPage为分页接口,PageIPage接口的一个实现类。

  1. 分页查询

Mybatis Plus的BaseMapperServiceImpl均提供了常用的分页查询的方法,例如:

BaseMapper的分页查询:

IPage<T> selectPage(IPage<T> page,Wrapper<T> queryWrapper);

ServiceImpl的分页查询:

// 无条件分页查询
IPage<T> page(IPage<T> page);
// 条件分页查询
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);

自定义Mapper 查询:

对于自定义SQL,也可以十分方便的完成分页查询,如下:

Mapper接口:

IPage<UserVo> selectPageVo(IPage<?> page, Integer state);

Mapper.xml

<select id="selectPageVo" resultType="xxx.xxx.xxx.UserVo">
    SELECT id,name FROM user WHERE state=#{state}
</select>

注意:Mapper.xml中的SQL只需实现查询list的逻辑即可,无需关注分页的逻辑。

具体的实例见下面的测试类:

首先编写一段测试代码:

@SpringBootTest
public class PageTest {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    //通用Service分页查询
    @Test
    public void testPageService() {
        Page<User> page = new Page<>(2, 3);
        Page<User> userPage = userService.page(page);
        userPage.getRecords().forEach(System.out::println);
    }

    //通用Mapper分页查询
    @Test
    public void testPageMapper() {
        IPage<User> page = new Page<>(2, 3);
        IPage<User> userPage = userMapper.selectPage(page, null);
        userPage.getRecords().forEach(System.out::println);
    }

    //自定义SQL分页查询
    @Test
    public void testCustomMapper() {
        IPage<User> page = new Page<>(2, 3);
        IPage<User> userPage = userMapper.selectUserPage(page);
        userPage.getRecords().forEach(System.out::println);
    }
}

对于自定义分页查询,在UserMapper中声明分页查询方法如下:

IPage<User> selectUserPage(IPage<User> page);

创建resources/mapper/UserMapper.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.atguigu.hellomp.mapper.UserMapper">
    <select id="selectUserPage" resultType="com.atguigu.hellomp.entity.User">
        select *
        from user
    </select>
</mapper>

注意:Mybatis-Plus中Mapper.xml文件路径默认为:classpath*:/mapper/**/*.xml,可在application.yml中配置以下参数进行修改:

mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml
posted @ 2024-07-08 15:53  LilyFlower  阅读(4)  评论(0编辑  收藏  举报