写在前面
MyBatis-Plus 提供了物理分页的功能,当我们使用分页查询时,需要先配置分页插件然后再调用对应的方法,简单的两步就可以完成分页。
配置定义
@Configuration
@EnableConfigurationProperties(value = {MybatisPlusProperties.class})
public class MybatisPlusConfig {
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
方法调用
// 查询条件:商品标题中包含'丝袜'并且状态为上架的商品
QueryWrapper<MallxSpu> queryWrapper = new QueryWrapper<>();
queryWrapper.like("title","丝袜").eq("statue",1);
// 开始查询,查询第一页,每页10条数据
// Map中的key为对象的属性名(驼峰)
IPage<MallxSpu> result = mallxSpuMapper.selectPage(new Page<>(1, 10), queryWrapper);
或者
// Map中的key为表字段名(下划线)
IPage<Map<String, Object>> result = mallxSpuMapper.selectMapsPage(new Page<>(1, 10), queryWrapper);
自定义SQL的分页一
传递参数Page对象到方法中便可以自动完成分页,分页参数Page必须是第一个,也可以传入继承了Page的自定义的分页对象。
public interface MallxSpuMapper extends BaseMapper<MallxSpu> {
@Select("SELECT * FROM MALLX_SPU WHERE STATUS = #{status}")
IPage<MallxSpu> getMallxSpuByStatus(Page<?> page, Integer status);
}
自定义SQL的分页二
①. 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.example.demo.mapper.UserInfoMapper">
<select id="getMallxSpuByStatus2" resultType="cn.hadoopx.mallx.entity.MallxSpu">
SELECT * FROM MALLX_SPU WHERE STATUS = #{status}
</select>
</mapper>
②. Mapper的定义
传递参数Page对象到方法中便可以自动完成分页,分页参数Page必须是第一个,也可以传入继承了Page的自定义的分页对象。
public interface MallxSpuMapper extends BaseMapper<MallxSpu> {
IPage<MallxSpu> getMallxSpuByStatus2(Page<?> page, Integer status);
}
本文详细介绍了如何在MyBatis-Plus中配置和使用物理分页功能。首先展示了如何在配置类中创建PaginationInterceptor,并设置相关参数。接着,通过实例演示了在Mapper接口和XML文件中定义SQL查询并结合Page对象实现分页的方法。此外,还提供了两种自定义SQL查询的分页方式,使得分页查询更加灵活。
6600

被折叠的 条评论
为什么被折叠?



