Home >Java >javaTutorial >How to implement SpringBoot MP simple paging query test
Importing the latest mp dependencies is the first step, otherwise nothing can be done with versions that are too low. It seems that the paging plug-in is not even added to versions below 3,1, so we use the latest 3.5 to ensure that everything is included:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.2</version> </dependency>
Here we need to know two plug-ins: mp’s core plug-in MybatisPlusInterceptor and automatic paging plug-in PaginationInnerInterceptor.
The source code of MybatisPlusInterceptor (removing the intermediate processing code):
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) {} }
We can find that it has a private attribute list List
InnerInterceptor source code:
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) { } }
It is not difficult to find that the content of this interface is roughly to set the default attributes. From the code point of view, it provides some logic to be executed before and after the default database operation execution period. Who Will the method that implements it gain new functionality?
Look at the source code of the PaginationInnerInterceptor plug-in:
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 {...........省略之后全部的内容........}
We can easily find that this method implements the methods in the InnerInterceptor interface, so we need to review its source code to clarify the logic.
We know the relationship between the paging plug-in and the core plug-in, that is, we can add the paging plug-in to the plug-in linked list inside the core plug-in to realize the use of multi-functional plug-ins.
Configure the mp plug-in and hand over the plug-in to spring management (we use springboot for testing so there is no need to use xml files):
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; } }
After configuration, write a Mapper interface:
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> { }
Create a service class for the interface (must follow the mp coding style):
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; } }
Here we can see that the specific method of paging is to first create a paging object, specify the page number and each page The size of the data on one page, and then determine the scope of the query operation, and use the query paging method selectPage(E page, Wapper
Test class:
@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()); }
Run to view the paging results:
We can find that all queries are performed normally according to the page number we passed in The corresponding page data is there, because each page I set up only displays one piece of data, so if the ID corresponds to the page number, it means the paging is successful.
The above is the detailed content of How to implement SpringBoot MP simple paging query test. For more information, please follow other related articles on the PHP Chinese website!