mybatis-plus分页查询的实现实例

页查询是一项常用的数据库查询方法,本文主要介绍了mybatis-plus分页查询的实现实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、官方文档
Mybatis-Plus分页插件:https://baomidou.com/pages/97710a/

PageHelper分页插件:MyBatis 分页插件 PageHelper

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);
}

执行结果:

查询出了表中满足条件的所有记录,说明默认情况下,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;
    }
}

再次执行单元测试:

先执行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&lt;User&gt; page = userMapper.selectPageByDto(PageDTO.of(1,10),userDto);
     
    page.getRecords().forEach(System.out::println);
}

下面是官网的一些说明:

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

个人建议:如果定义的方法名中包含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分页插件进行了对比。两者的使用都非常简单,在单一项目中任选一种,统一代码风格即可。

到此这篇关于mybatis-plus分页查询的实现实例的文章就介绍到这了,更多相关mybatis-plus分页查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持vb.net教程C#教程python教程SQL教程access 2010教程xin3721自学网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值