SpringBoot?MP簡單的分頁查詢測試實現(xiàn)步驟分解
導入最新的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) {} }
我們可以發(fā)現(xiàn)它有一個私有的屬性列表 List<InnerInterceptor> 而這個鏈表中的元素類型是InnerInterceptor。
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) { } }
不難發(fā)現(xiàn)這個接口的內容大致就是設置默認的屬性,從代碼的意思上就是提供默認的數(shù)據(jù)庫操作執(zhí)行時期前后執(zhí)行的一些邏輯,誰實現(xiàn)它的方法會得到新的功能?
再看看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 {...........省略之后全部的內容........}
我們不難發(fā)現(xiàn)它實現(xiàn)了來自于InnerInterceptor的方法,這里面的源碼有時間需要好好處處邏輯。
我們知道了分頁插件和核心插件的關系,也就是我們可以將分頁插件添加入核心插件內部的插件鏈表中去,從而實現(xiàn)多功能插件的使用。
配置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() { /*創(chuàng)建mp攔截器*/ MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); /*創(chuàng)建分頁插件*/ PaginationInnerInterceptor pagInterceptor = new PaginationInnerInterceptor(); /*設置請求的頁面大于最大頁容量后的請求操作,true回調第一頁,false繼續(xù)翻頁,默認翻頁*/ pagInterceptor.setOverflow(false); /*設置單頁分頁的條數(shù)限制*/ pagInterceptor.setMaxLimit(500L); /*設置數(shù)據(jù)庫類型*/ 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> { }
為接口創(chuàng)建一個服務類(一定按照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; /** * 根據(jù)傳入的頁碼進行翻頁 * * @param current 當前頁碼(已經(jīng)約定每頁數(shù)據(jù)量是1條) * @return 分頁對象 */ public Page<Product> page(Long current) { /*current首頁位置,寫1就是第一頁,沒有0頁之說,size每頁顯示的數(shù)據(jù)量*/ Page<Product> productPage = new Page<>(current, 1); /*條件查詢分頁*/ QueryWrapper<Product> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("status", 0); productMapper.selectPage(productPage, queryWrapper); return productPage; } }
到這里我們可以看到分頁的具體方法就是,先創(chuàng)建一個分頁對象,規(guī)定頁碼和每一頁的數(shù)據(jù)量的大小,其次確定查詢操作的范圍,并使用BaseMapper<T>給予我們的查詢分頁方法selectPage(E page,Wapper<T> queryWapper)進行查詢分頁的操作。
測試類:
@Test public void testPage(){ IPage<Product> productIPage = productService.page(2L); productIPage.getRecords().forEach(System.out::println); System.out.println("當前頁碼"+productIPage.getCurrent()); System.out.println("每頁顯示數(shù)量"+productIPage.getSize()); System.out.println("總頁數(shù)"+productIPage.getPages()); System.out.println("數(shù)據(jù)總量"+productIPage.getTotal()); }
運行查看分頁結果:
我們可以發(fā)現(xiàn)都正常的按照我們傳入的頁碼去查詢對應的頁數(shù)據(jù)了,因為我設置的每頁只展示一條數(shù)據(jù),所以ID如果對應頁碼就說明分頁成功。
到此這篇關于SpringBoot MP簡單的分頁查詢測試實現(xiàn)步驟分解的文章就介紹到這了,更多相關SpringBoot MP分頁查詢測試內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring boot定時任務的原理及動態(tài)創(chuàng)建詳解
這篇文章主要給大家介紹了關于Spring boot定時任務的原理及動態(tài)創(chuàng)建的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-03-03Spring Boot mybatis-config 和 log4j 輸出sql 日志的方式
這篇文章主要介紹了Spring Boot mybatis-config 和 log4j 輸出sql 日志的方式,本文通過實例圖文相結合給大家介紹的非常詳細,需要的朋友可以參考下2021-07-07