mybatis-plus分页查询详解

简介: mybatis-plus分页查询详解

前言


例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


一、官方文档


Mybatis-Plus分页插件:https://baomidou.com/pages/97710a/


PageHelper分页插件:https://pagehelper.github.io/


Tip⚠️:

官网链接,第一手资料。


二、内置的分页方法


1、内置方法

在Mybatis-Plus的BaseMapper中,已经内置了2个支持分页的方法:

public interface BaseMapper<T> extends Mapper<T> {
    <P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);
    <P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);
          ……
    }


2、selectPage单元测试

使用selectPage方法分页查询年纪age = 13的用户。


@Test
    public void testPage() {
        System.out.println("----- selectPage method test ------");
        //分页参数
        Page<User> page = Page.of(1,10);
        //queryWrapper组装查询where条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAge,13);
        userMapper.selectPage(page,queryWrapper);
        page.getRecords().forEach(System.out::println);
    }


执行结果:

44.png

查询出了表中满足条件的所有记录,说明默认情况下,selectPage方法并不能实现分页查询。


3、PaginationInnerInterceptor分页插件配置

mybatis-plus中的分页查询功能,需要PaginationInnerInterceptor分页插件的支持,否则分页查询功能不能生效。

@Configuration
public class MybatisPlusConfig {
    /**
     * 新增分页拦截器,并设置数据库类型为mysql
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}


再次执行单元测试:

43.png

先执行count查询查询满足条件的记录总数,然后执行limit分页查询,查询分页记录,说明分页查询生效。


三、分页原理分析


查看PaginationInnerInterceptor拦截器中的核心实现:

//select查询请求的前置方法
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    //根据请求参数来判断是否采用分页查询,参数中含有IPage类型的参数,则执行分页
    IPage<?> page = (IPage)ParameterUtils.findPage(parameter).orElse((Object)null);
    if (null != page) {
        boolean addOrdered = false;
        String buildSql = boundSql.getSql();
        List<OrderItem> orders = page.orders();
        if (CollectionUtils.isNotEmpty(orders)) {
            addOrdered = true;
            buildSql = this.concatOrderBy(buildSql, orders);
        }
        //根据page参数,组装分页查询sql
        Long _limit = page.maxLimit() != null ? page.maxLimit() : this.maxLimit;
        if (page.getSize() < 0L && null == _limit) {
            if (addOrdered) {
                PluginUtils.mpBoundSql(boundSql).sql(buildSql);
            }
        } else {
            this.handlerLimit(page, _limit);
            IDialect dialect = this.findIDialect(executor);
            Configuration configuration = ms.getConfiguration();
            DialectModel model = dialect.buildPaginationSql(buildSql, page.offset(), page.getSize());
            MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
            List<ParameterMapping> mappings = mpBoundSql.parameterMappings();
            Map<String, Object> additionalParameter = mpBoundSql.additionalParameters();
            model.consumers(mappings, configuration, additionalParameter);
            mpBoundSql.sql(model.getDialectSql());
            mpBoundSql.parameterMappings(mappings);
        }
    }
}


再来看看ParameterUtils.findPage()方法的实现:

//发现参数中的IPage对象
public static Optional<IPage> findPage(Object parameterObject) {
    if (parameterObject != null) {
        //如果是多个参数,会转为map对象;只要任意一个value中包含IPage类型的对象,返回IPage对象
        if (parameterObject instanceof Map) {
            Map<?, ?> parameterMap = (Map)parameterObject;
            Iterator var2 = parameterMap.entrySet().iterator();
            while(var2.hasNext()) {
                Entry entry = (Entry)var2.next();
                if (entry.getValue() != null && entry.getValue() instanceof IPage) {
                    return Optional.of((IPage)entry.getValue());
                }
            }
         //如果只有单个参数,且类型为IPage,则返回IPage对象
        } else if (parameterObject instanceof IPage) {
            return Optional.of((IPage)parameterObject);
        }
    }
    return Optional.empty();
}


小结:

mybatis-plus分页查询的实现原理:

1、由分页拦截器PaginationInnerInterceptor拦截所有查询请求,在执行查询前判断参数中是否包含IPage类型的参数。

2、如果包含IPage类型的参数,则根据分页信息,重新组装成分页查询的SQL。


四、自定义分页方法


搞清楚mybatis-plus中分页查询的原理,我们来自定义分页查询方法。


这里我使用的是mybatis-plus 3.5.2的版本。

<dependency>
       <groupId>com.baomidou</groupId>
       <artifactId>mybatis-plus-boot-starter</artifactId>
       <version>3.5.2</version>
   </dependency>


在UserMapper中新增selectPageByDto方法。

public interface UserMapper extends CommonMapper<User> {
    /**
     * 不分页dto条件查询
     * @param userDto
     * @return
     */
    List<User> selectByDto(@Param("userDto") UserDto userDto);
    /**
     * 支持分页的dto条件查询
     * @param page
     * @param userDto
     * @return
     */
    IPage<User> selectPageByDto(IPage<User> page,@Param("userDto") UserDto userDto);
}


说明:

1、mybatis-plus中分页接口需要包含一个IPage类型的参数。

2、多个实体参数,需要添加@Param参数注解,方便在xml中配置sql时获取参数值。


UserMapper.xml中的分页sql配置:

这里由于selectByDto和selectPageByDto两个方法都是根据dto进行查询,

sql语句完全一样,所以将相同的sql抽取了出来,然后用include标签去引用。

<sql id="selectByDtoSql">
        select  * from user t
        <where>
            <if test="userDto.name != null and userDto.name != '' ">
                AND t.name like CONCAT('%',#{userDto.name},'%')
            </if>
            <if test="userDto.age != null">
                AND t.age = #{userDto.age}
            </if>
        </where>
    </sql>
    <select id="selectByDto" resultType="com.laowan.mybatis_plus.model.User">
       <include refid="selectByDtoSql"/>
    </select>
    <select id="selectPageByDto" resultType="com.laowan.mybatis_plus.model.User">
        <include refid="selectByDtoSql"/>
    </select>



1、2种分页写法

方式一:

Page对象既作为参数,也作为查询结果接受体

@Test
  public void testSelectPageByDto() {
       System.out.println("----- SelectPageByDto method test ------");
       //分页参数Page,也作为查询结果接受体
       Page<User> page = Page.of(1,10);
       //查询参数
       UserDto userDto = new UserDto();
       userDto.setName("test");
       userMapper.selectPageByDto(page,userDto);
       page.getRecords().forEach(System.out::println);
   }


方式二:

Page作为参数,用一个新的IPage对象接受查询结果。

@Test
    public void testSelectPageByDto() {
        System.out.println("----- SelectPageByDto method test ------");
        //查询参数
        UserDto userDto = new UserDto();
        userDto.setName("test");
        //PageDTO.of(1,10)对象只作为查询参数,
        IPage<User> page = userMapper.selectPageByDto(PageDTO.of(1,10),userDto);
        page.getRecords().forEach(System.out::println);
    }


下面是官网的一些说明:

42.png

这是官网针对自定义分页的说明。


个人建议:如果定义的方法名中包含Page说明是用来分页查询的,返回结果尽量用IPage,而不要用List。防止出现不必要的错误,也更符合见名之一和单一指责原则。


2、利用page.convert方法实现Do到Vo的转换

public IPage<UserVO> list(PageRequest request) {
  IPage<UserDO> page = new Page(request.getPageNum(), request.pageSize());
  LambdaQueryWrapper<UserDO> qw = Wrappers.lambdaQuery();
  page  = userMapper.selectPage(page, qw);
  return page.convert(u->{ 
    UserVO v = new UserVO();
    BeanUtils.copyProperties(u, v);
    return v;
  });
}


五、分页插件 PageHelper


很多人已经习惯了在mybatis框架下使用PageHelper进行分页查询,在mybatis-plus框架下依然也可以使用,和mybatis-plus框架自带的分页插件没有明显的高下之分。


个人认为mybatis-plus的分页实现可以从方法命名、方法传参方面更好的规整代码。而PageHelper的实现对代码的侵入性更强,不符合单一指责原则。


推荐在同一个项目中,只选用一种分页方式,统一代码风格。


PageHelper的使用:


1.引入maven依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>最新版本</version>
</dependency>


2.PageHelper分页查询

代码如下(示例):

//获取第1页,10条内容,默认查询总数count
PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectAll();
//用PageInfo对结果进行包装
PageInfo page = new PageInfo(list);


总结


本文主要对mybatis-plus分页查询的原理和使用进行了详细介绍。


1、要开启mybatis-plus分页查询功能首先需要配置PaginationInnerInterceptor分页查询插件。


2、PaginationInnerInterceptor分页查询插件的实现原理是:拦截所有查询请求,分析查询参数中是否包含IPage类型的参数。如果有则根据分页信息和数据库类型重组sql。


3、提供了2种分页查询的写法。


4、和经典的PageHelper分页插件进行了对比。两者的使用都非常简单,在单一项目中任选一种,统一代码风格即可。

目录
相关文章
|
1月前
Mybatis+mysql动态分页查询数据案例——测试类HouseDaoMybatisImplTest)
Mybatis+mysql动态分页查询数据案例——测试类HouseDaoMybatisImplTest)
21 1
|
1月前
|
Java 关系型数据库 数据库连接
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
26 1
|
1月前
Mybatis+mysql动态分页查询数据案例——条件类(HouseCondition)
Mybatis+mysql动态分页查询数据案例——条件类(HouseCondition)
15 1
|
1月前
Mybatis+mysql动态分页查询数据案例——分页工具类(Page.java)
Mybatis+mysql动态分页查询数据案例——分页工具类(Page.java)
22 1
|
1月前
Mybatis+mysql动态分页查询数据案例——房屋信息的实现类(HouseDaoMybatisImpl)
Mybatis+mysql动态分页查询数据案例——房屋信息的实现类(HouseDaoMybatisImpl)
22 2
|
5月前
|
Java 数据库连接 数据库
MyBatis分页查询及特殊字符的处理
MyBatis分页查询及特殊字符的处理
60 0
|
1月前
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
15 1
|
1月前
|
Java 数据库连接 mybatis
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
20 1
|
1月前
Mybatis+mysql动态分页查询数据案例——配置映射文件(HouseDaoMapper.xml)
Mybatis+mysql动态分页查询数据案例——配置映射文件(HouseDaoMapper.xml)
15 1
|
1月前
Mybatis+mysql动态分页查询数据案例——房屋信息的接口(IHouseDao)
Mybatis+mysql动态分页查询数据案例——房屋信息的接口(IHouseDao)
12 1