As a Java programmer, you can even write simple paging functions, so sorry!

What I want to say today is that it can be implemented more simply and efficiently when we operate the database. The ready-made CRUD interface can be directly called, which is convenient and fast. There is no need to write complex SQL. It is simple and easy to understand, and there is not much to say.

1. Methods in Utils.java tool class

1 /**  2  * 获取Sort
 3  *
 4  * @param direction  - 排序方向
 5  * @param column - 用于排序的字段
 6  */
 7 public static Sort getSort(String direction,String column){
 8     Sort sort = null;
 9     if(column == null || column == "") return null;
10     if(direction.equals("asc")||direction.equals("ASC")){
11         sort =  Sort.by(Sort.Direction.ASC,column);
12     }else {
13         sort =  Sort.by(Sort.Direction.DESC,column);
14     }
15     return sort;
16 }
17 /**
18  * 获取分页
19  * @param pageNumber 当前页
20  * @param pageSize  页面大小
21  * @param sort 排序;sort为空则不排序只分页
22  * @return 分页对象
23  */
24 public static Pageable getPageable(int pageNumber,int pageSize,Sort sort){
25    if(sort!=null){
26        return PageRequest.of(pageNumber,pageSize,sort);
27    }
28        return PageRequest.of(pageNumber,pageSize);
29 }
30  /**
31      * 判断String是否为空
32      * @param str
33      * @return
34      */
35     private static boolean isEmpty(String str){
36         if(str.equals(null)||str.equals("")) return true;
37         return false;
38     } 

2. Implementation class

Here the query related parameters are passed by the front end, so the default values ​​are used. The query conditions can be dynamic with multiple conditions, and the sorting can also be dynamic, as long as the sorting field and the sorting direction are checked in.

@Override
public Page<User> findAll() {
    // 创建测试对象
    User user = new User();
    user.setName("1");
    Sort sort = Utils.getSort("asc","name");
    Pageable pageable = Utils.getPageable(0,5,sort);
    // 调用组装查询条件方法
    Specification<User> spec = getSpecification(user);
    return userRepository.findAll(spec,pageable);
}

/**
 * 组装查询条件
 * @param user -查询相关对象
 * @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. Write like this in the repository class

@Repository

public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {}

At last

Reply to the data by private message to receive a summary of Java interview questions from a major manufacturer + Alibaba Taishan manual + a learning guide for knowledge points + a summary of Java core knowledge points in a 300-page pdf document!

The content of these materials are all the knowledge points that the interviewer must ask during the interview. The chapter includes many knowledge points, including basic knowledge, Java collections, JVM, multi-threaded concurrency, spring principles, microservices, Netty and RPC, Kafka , Diary, design pattern, Java algorithm, database, Zookeeper, distributed cache, data structure, etc. file

Guess you like

Origin blog.csdn.net/weixin_46577306/article/details/108247700