说明
尝试做一个springboot的框架demo,不足之处,请留言指出,不胜感谢。
pom修改依赖
我是vscode,ctrl+shift+p
调出命令面板:
- maven : add a dependency
- select a maven project
- 输入pagehelper,选择 com.github.pagehelper
- 确认后自动修改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()});
......
}
修改代码
经过上面两步,插件已经准备好了。现在改写一下代码,传入分页的参数就可以了。
BaseCondition
查询条件改一下,加入两个字段。这样,作为controller参数,也能接收到分页信息。
@Data
public abstract class BaseCondition {
......
//分页,第几页
private int pageNum;
//分页,每页大小
private int pageSize;
......
}
IBaseService
这里需要提前设定分页信息,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测试一下:
修改返回格式
在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)) ;
}
......
对应Controller中也修改一下:
@RequestMapping(value = "/list", method = RequestMethod.GET)
public PageInfo<OrderBean> orders(OrderCondition orderCondition) {
return orderService.findAll(orderCondition);
}
同样的输入参数,PostMan测试返回: