Java簡(jiǎn)單高效實(shí)現(xiàn)分頁(yè)功能
今天想說(shuō)的就是能夠在我們操作數(shù)據(jù)庫(kù)的時(shí)候更簡(jiǎn)單的更高效的實(shí)現(xiàn),現(xiàn)成的CRUD接口直接調(diào)用,方便快捷,不用再寫(xiě)復(fù)雜的sql,帶嗎簡(jiǎn)單易懂,話不多說(shuō)上方法
1、Utils.java工具類中的方法
/** 2 * 獲取Sort * * @param direction - 排序方向 * @param column - 用于排序的字段 */ public static Sort getSort(String direction,String column){ Sort sort = null; if(column == null || column == '') return null; if(direction.equals('asc')||direction.equals('ASC')){ sort = Sort.by(Sort.Direction.ASC,column); }else { sort = Sort.by(Sort.Direction.DESC,column); } return sort; } /** * 獲取分頁(yè) * @param pageNumber 當(dāng)前頁(yè) * @param pageSize 頁(yè)面大小 * @param sort 排序;sort為空則不排序只分頁(yè) * @return 分頁(yè)對(duì)象 */ public static Pageable getPageable(int pageNumber,int pageSize,Sort sort){ if(sort!=null){ return PageRequest.of(pageNumber,pageSize,sort); } return PageRequest.of(pageNumber,pageSize); } /** * 判斷String是否為空 * @param str * @return */ private static boolean isEmpty(String str){ if(str.equals(null)||str.equals('')) return true; return false; }
2、實(shí)現(xiàn)類
這里查詢相關(guān)參數(shù)是前端傳的,所以用默認(rèn)值了,查詢條件可以是多條件動(dòng)態(tài),排序也可以是動(dòng)態(tài)的,只要傳排序字段和排序方向?qū)μ?hào)入座即可。
@Overridepublic Page<User> findAll() { // 創(chuàng)建測(cè)試對(duì)象 User user = new User(); user.setName('1'); Sort sort = Utils.getSort('asc','name'); Pageable pageable = Utils.getPageable(0,5,sort); // 調(diào)用組裝查詢條件方法 Specification<User> spec = getSpecification(user); return userRepository.findAll(spec,pageable);}/** * 組裝查詢條件 * @param user -查詢相關(guān)對(duì)象 * @return 返回組裝過(guò)的多查詢條件 */private Specification<User> getSpecification(User user) { Specification<User> specification = new Specification<User>() { @Override public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { List<Predicate> predicates = new ArrayList<>(); // 判斷條件不為空 if(!Utils.isEmpty(user.getName())){predicates.add(criteriaBuilder.like(root.get('name'),user.getName())); } return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction(); } }; return specification;}
3.repository類中這么寫(xiě)
@Repositorypublic interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP的Global.asa文件技巧用法2. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)3. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法4. ASP中常用的22個(gè)FSO文件操作函數(shù)整理5. SharePoint Server 2019新特性介紹6. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單7. Vue+elementUI下拉框自定義顏色選擇器方式8. PHP函數(shù)原理理解詳談9. XML入門的常見(jiàn)問(wèn)題(四)10. 使用css實(shí)現(xiàn)全兼容tooltip提示框
