今天想說的就是能夠在我們操作數(shù)據(jù)庫(kù)的時(shí)候更簡(jiǎn)單的更高效的實(shí)現(xiàn),現(xiàn)成的CRUD接口直接調(diào)用,方便快捷,不用再寫復(fù)雜的sql,帶嗎簡(jiǎn)單易懂,話不多說上方法
1、Utils.java工具類中的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
/** 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; } /** * 獲取分頁 * @param pageNumber 當(dāng)前頁 * @param pageSize 頁面大小 * @param sort 排序;sort為空則不排序只分頁 * @return 分頁對(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)入座即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
@Override public 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 返回組裝過的多查詢條件 */ 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類中這么寫
@Repository
public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/MonsterJ/p/13567857.html