使用springdata JPA实现分页
1.创建dao,继承JpaSpecificationExecutor和PagingAndSortingRepository。如下:
public interface CodeEntryDao extends JpaSpecificationExecutor,PagingAndSortingRepository<CodeEntry,Long> </pre> 2.提供findAll接口,传入Specification 和Pageable 两个参数。如下:
public PagefindAll( Specification spec,Pageable pageRequest); </pre> 3.在service中调用findAll时创建Specification和Pageable,Specification是查询条件,Pageable包含pageNumber,pageSize,sort等参数。创建过程如下。
/** * 创建分页请求. */ private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) { Sort sort = null; if ("auto".equals(sortType)) { sort = new Sort(Sort.Direction.DESC, "id"); } else if ("id".equals(sortType)) { sort = new Sort(Sort.Direction.ASC, "entryId"); } return new PageRequest(pageNumber - 1, pagzSize, sort); } /** * 创建动态查询条件组合. */ private SpecificationbuildSpecification(Map<String, Object> searchParams) { List< SearchFilter> filters = (List ) SearchFilter.parse(searchParams); Specification spec = DynamicSpecifications.bySearchFilter(filters, CodeEntry.class); return spec; } </pre> 创建Specification时需要要有searchFilter和DynamicSpecifications]类支持,点击去github克隆源码
原创文章,转载请注明:转载自:使用springdata JPA实现分页