說明
嘗試做一個(gè)springboot的框架demo钧舌,不足之處禁熏,請(qǐng)留言指出垦巴,不勝感謝媳搪。
pom修改依賴
我是vscode,ctrl+shift+p
調(diào)出命令面板:
- maven : add a dependency
- select a maven project
- 輸入pagehelper骤宣,選擇 com.github.pagehelper
- 確認(rèn)后自動(dòng)修改pom文件:如下
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.11</version>
</dependency>
修改DataSourceConfig
引入Mybatis插件PageHelper
@Bean(name = "mybatisSqlSessionFactory")
@Primary
@DependsOn(value = "springContextUtil")
public SqlSessionFactory sqlSessionFactory(@Qualifier("mybatisDataSource") DataSource dataSource) throws Exception {
......
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties = new Properties();
properties.setProperty("helperDialect", "mysql");
properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("supportMethodsArguments", "true");
pageInterceptor.setProperties(properties);
bean.setPlugins(new Interceptor[] { pageInterceptor()});
......
}
修改代碼
經(jīng)過上面兩步秦爆,插件已經(jīng)準(zhǔn)備好了。現(xiàn)在改寫一下代碼涯雅,傳入分頁的參數(shù)就可以了鲜结。
BaseCondition
查詢條件改一下展运,加入兩個(gè)字段活逆。這樣,作為controller參數(shù)拗胜,也能接收到分頁信息蔗候。
@Data
public abstract class BaseCondition {
......
//分頁,第幾頁
private int pageNum;
//分頁埂软,每頁大小
private int pageSize;
......
}
IBaseService
這里需要提前設(shè)定分頁信息锈遥,PageHelper.startPage
;具體代碼如下:
public interface IBaseService<Bean,Condition> {
......
default List<Bean> findAll(@Param("conditionQC") Condition condition){
BaseCondition baseCondition = (BaseCondition) condition;
PageHelper.startPage(baseCondition.getPageNum(),baseCondition.getPageSize());
return getBaseDao().findAll(condition);
}
......
使用postman測(cè)試一下:
在這里插入圖片描述
修改返回格式
在IBaseService中勘畔,將返回信息封裝一下:
public interface IBaseService<Bean,Condition> {
......
default PageInfo<Bean> findAll(@Param("conditionQC") Condition condition){
BaseCondition baseCondition = (BaseCondition) condition;
PageHelper.startPage(baseCondition.getPageNum(),baseCondition.getPageSize());
return new PageInfo<Bean>(getBaseDao().findAll(condition)) ;
}
......
對(duì)應(yīng)Controller中也修改一下:
@RequestMapping(value = "/list", method = RequestMethod.GET)
public PageInfo<OrderBean> orders(OrderCondition orderCondition) {
return orderService.findAll(orderCondition);
}
同樣的輸入?yún)?shù)所灸,PostMan測(cè)試返回:
在這里插入圖片描述