SpringBoot MP简单的分页查询测试怎么实现
导入最新的mp依赖是第一步不然太低的版本什么都做不了,3,1以下的好像连分页插件都没有加进去,所以我们用最新的3.5的,保证啥都有:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.2</version> </dependency>
这里我们需要认识两个插件:mp的核心插件MybatisPlusInterceptor与自动分页插件PaginationInnerInterceptor。
MybatisPlusInterceptor的源码(去掉中间的处理代码):
public class MybatisPlusInterceptor implements Interceptor { private List<InnerInterceptor> interceptors = new ArrayList(); public MybatisPlusInterceptor() {} public Object intercept(Invocation invocation) throws Throwable {} public Object plugin(Object target) {} public void addInnerInterceptor(InnerInterceptor innerInterceptor) {} public List<InnerInterceptor> getInterceptors() {} public void setProperties(Properties properties) {} public void setInterceptors(final List<InnerInterceptor> interceptors) {} }
我们可以发现它有一个私有的属性列表 List
InnerInterceptor源码:
public interface InnerInterceptor { default boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { return true; } default void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { } default boolean willDoUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException { return true; } default void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException { } default void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) { } default void beforeGetBoundSql(StatementHandler sh) { } default void setProperties(Properties properties) { } }
不难发现这个接口的内容大致就是设置默认的属性,从代码的意思上就是提供默认的数据库操作执行时期前后执行的一些逻辑,谁实现它的方法会得到新的功能?
再看看PaginationInnerInterceptor插件的源码:
public class PaginationInnerInterceptor implements InnerInterceptor { protected static final List<SelectItem> COUNT_SELECT_ITEM = Collections.singletonList((new SelectExpressionItem((new Column()).withColumnName("COUNT(*)"))).withAlias(new Alias("total"))); protected static final Map<String, MappedStatement> countMsCache = new ConcurrentHashMap(); protected final Log logger = LogFactory.getLog(this.getClass()); protected boolean overflow; protected Long maxLimit; private DbType dbType; private IDialect dialect; protected boolean optimizeJoin = true; public PaginationInnerInterceptor(DbType dbType) { this.dbType = dbType; } public PaginationInnerInterceptor(IDialect dialect) { this.dialect = dialect; } public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { IPage<?> page = (IPage)ParameterUtils.findPage(parameter).orElse((Object)null); if (page != null && page.getSize() >= 0L && page.searchCount()) { MappedStatement countMs = this.buildCountMappedStatement(ms, page.countId()); BoundSql countSql; if (countMs != null) { countSql = countMs.getBoundSql(parameter); } else { countMs = this.buildAutoCountMappedStatement(ms); String countSqlStr = this.autoCountSql(page, boundSql.getSql()); MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql); countSql = new BoundSql(countMs.getConfiguration(), countSqlStr, mpBoundSql.parameterMappings(), parameter); PluginUtils.setAdditionalParameter(countSql, mpBoundSql.additionalParameters()); } CacheKey cacheKey = executor.createCacheKey(countMs, parameter, rowBounds, countSql); List<Object> result = executor.query(countMs, parameter, rowBounds, resultHandler, cacheKey, countSql); long total = 0L; if (CollectionUtils.isNotEmpty(result)) { Object o = result.get(0); if (o != null) { total = Long.parseLong(o.toString()); } } page.setTotal(total); return this.continuePage(page); } else { return true; } } public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {...........省略之后全部的内容........}
我们可以轻易地发现这个方法实现了InnerInterceptor接口中的方法,所以我们需要好好审查它的源代码来理清逻辑。
我们知道了分页插件和核心插件的关系,也就是我们可以将分页插件添加入核心插件内部的插件链表中去,从而实现多功能插件的使用。
配置mp插件,并将插件交由spring管理(我们用的是springboot进行测试所以不需要使用xml文件):
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; @Configuration public class MpConfig { /*分页插件的配置*/ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { /*创建mp拦截器*/ MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); /*创建分页插件*/ PaginationInnerInterceptor pagInterceptor = new PaginationInnerInterceptor(); /*设置请求的页面大于最大页容量后的请求操作,true回调第一页,false继续翻页,默认翻页*/ pagInterceptor.setOverflow(false); /*设置单页分页的条数限制*/ pagInterceptor.setMaxLimit(500L); /*设置数据库类型*/ pagInterceptor.setDbType(DbType.MYSQL); /*将分页拦截器添加到mp拦截器中*/ interceptor.addInnerInterceptor(pagInterceptor); return interceptor; } }
配置完之后写一个Mapper接口:
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.hlc.mp.entity.Product; import org.apache.ibatis.annotations.Mapper; @Mapper public interface ProductMapper extends BaseMapper<Product> { }
为接口创建一个服务类(一定按照mp编码的风格来):
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.hlc.mp.entity.Product; import com.hlc.mp.mapper.ProductMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service(value = "ProductService") public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IService<Product> { @Autowired ProductMapper productMapper; /** * 根据传入的页码进行翻页 * * @param current 当前页码(已经约定每页数据量是1条) * @return 分页对象 */ public Page<Product> page(Long current) { /*current首页位置,写1就是第一页,没有0页之说,size每页显示的数据量*/ Page<Product> productPage = new Page<>(current, 1); /*条件查询分页*/ QueryWrapper<Product> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("status", 0); productMapper.selectPage(productPage, queryWrapper); return productPage; } }
到这里我们可以看到分页的具体方法就是,先创建一个分页对象,规定页码和每一页的数据量的大小,其次确定查询操作的范围,并使用BaseMapper
测试类:
@Test public void testPage(){ IPage<Product> productIPage = productService.page(2L); productIPage.getRecords().forEach(System.out::println); System.out.println("当前页码"+productIPage.getCurrent()); System.out.println("每页显示数量"+productIPage.getSize()); System.out.println("总页数"+productIPage.getPages()); System.out.println("数据总量"+productIPage.getTotal()); }
运行查看分页结果:
我们可以发现都正常的按照我们传入的页码去查询对应的页数据了,因为我设置的每页只展示一条数据,所以ID如果对应页码就说明分页成功。
以上是SpringBoot MP简单的分页查询测试怎么实现的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Jasypt介绍Jasypt是一个java库,它允许开发员以最少的努力为他/她的项目添加基本的加密功能,并且不需要对加密工作原理有深入的了解用于单向和双向加密的高安全性、基于标准的加密技术。加密密码,文本,数字,二进制文件...适合集成到基于Spring的应用程序中,开放API,用于任何JCE提供程序...添加如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter2.1.1Jasypt好处保护我们的系统安全,即使代码泄露,也可以保证数据源的

使用场景1、下单成功,30分钟未支付。支付超时,自动取消订单2、订单签收,签收后7天未进行评价。订单超时未评价,系统默认好评3、下单成功,商家5分钟未接单,订单取消4、配送超时,推送短信提醒……对于延时比较长的场景、实时性不高的场景,我们可以采用任务调度的方式定时轮询处理。如:xxl-job今天我们采

听歌是一件很常见的事情,相信无论在哪里,很多朋友都会做。你平常用来听歌的软件是什么呢?是不是像我一样使用QQ音乐?我目前就是用QQ音乐来听歌,而且不仅可以在手机上用,还可以在Mac电脑上使用。除了在线听歌,我们还可以把QQ音乐中喜欢的歌曲下载到电脑上。不过,Mac版QQ音乐下载的歌曲不是我们需要的格式,我们需要的是MP3格式的音乐,那么如何将Mac版QQ音乐下载的歌曲导出为MP3格式呢?如何将在Mac版QQ音乐下载的歌曲导出并转换为MP3格式?如果您想将Mac版QQ音乐下载的歌曲导出并转换为MP

一、Redis实现分布式锁原理为什么需要分布式锁在聊分布式锁之前,有必要先解释一下,为什么需要分布式锁。与分布式锁相对就的是单机锁,我们在写多线程程序时,避免同时操作一个共享变量产生数据问题,通常会使用一把锁来互斥以保证共享变量的正确性,其使用范围是在同一个进程中。如果换做是多个进程,需要同时操作一个共享资源,如何互斥呢?现在的业务应用通常是微服务架构,这也意味着一个应用会部署多个进程,多个进程如果需要修改MySQL中的同一行记录,为了避免操作乱序导致脏数据,此时就需要引入分布式锁了。想要实现分

springboot读取文件,打成jar包后访问不到最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

在Springboot+Mybatis-plus不使用SQL语句进行多表添加操作我所遇到的问题准备工作在测试环境下模拟思维分解一下:创建出一个带有参数的BrandDTO对象模拟对后台传递参数我所遇到的问题我们都知道,在我们使用Mybatis-plus中进行多表操作是极其困难的,如果你不使用Mybatis-plus-join这一类的工具,你只能去配置对应的Mapper.xml文件,配置又臭又长的ResultMap,然后再去写对应的sql语句,这种方法虽然看上去很麻烦,但具有很高的灵活性,可以让我们

SpringBoot和SpringMVC都是Java开发中常用的框架,但它们之间有一些明显的差异。本文将探究这两个框架的特点和用途,并对它们的差异进行比较。首先,我们来了解一下SpringBoot。SpringBoot是由Pivotal团队开发的,它旨在简化基于Spring框架的应用程序的创建和部署。它提供了一种快速、轻量级的方式来构建独立的、可执行

1、自定义RedisTemplate1.1、RedisAPI默认序列化机制基于API的Redis缓存实现是使用RedisTemplate模板进行数据缓存操作的,这里打开RedisTemplate类,查看该类的源码信息publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//声明了key、value的各种序列化方式,初始值为空@NullableprivateRedisSe
