添加maven配置:
com.github.pagehelper pagehelper 4.1.6
添加Bean:
//配置mybatis的分页插件pageHelper @Bean public PageHelper pageHelper(){ PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); //设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 properties.setProperty("offsetAsPageNum","true"); //设置为true时,使用RowBounds分页会进行count查询 properties.setProperty("rowBoundsWithCount","true"); //设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 //properties.setProperty("pageSizeZero","true"); //禁用合理化,启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 properties.setProperty("reasonable","false"); //配置mysql数据库的方言 properties.setProperty("dialect","mysql"); //配置mysql数据库的方言 pageHelper.setProperties(properties); return pageHelper; }
SqlSessionFactory:
@Bean public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource,PageHelper pageHelper) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); Resource[] mappers = (new PathMatchingResourcePatternResolver()) .getResources("classpath*:mybatis_mapper/*Mapper.xml"); sessionFactory.setMapperLocations(mappers); sessionFactory.setPlugins(new Interceptor[]{pageHelper}); return sessionFactory.getObject(); }
应用:
public PageInfoselectListByParentKey(String parentKey){ PageHelper.startPage(2,3); List list=mapper.selectListByParentKey(parentKey); PageInfo pageInfo = new PageInfo<>(list); return pageInfo; }
封装返回的PageInfo
public class PageResult { private ModelMapper modelMapper=SpringUtils.getBean(ModelMapper.class); private PageInfo pageInfo; private Class aClass; public PageResult(PageInfo _pageInfo ){ this.pageInfo=_pageInfo; } /** * * @param _pageInfo pageHelper的实例 * @param _aClass list输出类型,如果aClass不为空,就将list转换为aClass类型,反之则不进行转换 */ public PageResult(PageInfo _pageInfo,Class _aClass){ this.pageInfo=_pageInfo; this.aClass=_aClass; } private Integer pageIndex; private Integer pageSize; private Long totalCount; private Integer totalPages; private List list; public Integer getPageIndex() { return pageInfo.getPageNum(); } public Integer getPageSize() { return pageInfo.getPageSize(); } public Long getTotalCount() { return pageInfo.getTotal(); } public Integer getTotalPages(){ return pageInfo.getPages(); } public List getList() { List list= pageInfo.getList(); if(null!=aClass) { List list2 = new ArrayList(); list.forEach(x -> { list2.add(modelMapper.map(x, aClass)); }); return list2; }else{ return list; } }}
调用:
PageHelper.startPage(request.getPageIndex(),request.getPageSize()); Listlist=dataDictBizFacade.selectListByCondition(request.getDictKey(),request.getDictDesc(),request.getParentKey()); PageResult result=new PageResult(new PageInfo<>(list),DataDictResponse.class); response.setData(result);