Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

hibernate - Spring boot JPA Specification API with Pagination and Sorting

Im trying to implement a search in spring boot. Since the search params is dynamic, i had to go for specification api. My requirement is to search for orders given certain params and sort those orders by creation date. Since data can be large, the api should also support for pagination. Below is the code snipped of the predicates.

public search(OrderSearchCriteria searchCriteria, Integer pageNo, Integer pageSize) {
      Pageable pageRequest = (!ObjectUtils.isEmpty(pageNo) && !ObjectUtils.isEmpty(pageSize))
                            ? PageRequest.of(pageNo, pageSize)
                            : Pageable.unpaged();

    Page<Order> ordersPage = this.dao.findAll(((Specification<Order>)(root, query, criteriaBuilder) -> {         
        
        // my search params, its more than what is shown here
        Long id = searchCriteria.getId();
        Priority priority = searchCriteria.getPriority();
      
        List<Predicate> predicates = new ArrayList<>();
        if(!ObjectUtils.isEmpty(id))
            predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("id"), id)));
         if(!ObjectUtils.isEmpty(priority))
            predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("priority"), priority)));
        
        // This line is causing the issue
        query.orderBy(criteriaBuilder.desc(root.get("creationDate")));
        return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
    }), pageRequest);

The issue is, if i add this sort by line query.orderBy(criteriaBuilder.desc(root.get("creationDate"))) Pagination is not working. page 0 and page 1 both shows same result(same order) given size as 1. But page 2 shows different result as expected. But if i remove the sort by line shown above, the code is working as expected. How do i support both pagination and sorting without having these issues? i tried applying sort in pagerequest as well. But same issue PageRequest.of(pageNo, size, sort.by(DESC, "creationDate")). Appreciate help.

question from:https://stackoverflow.com/questions/65942898/spring-boot-jpa-specification-api-with-pagination-and-sorting

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What do you mean by "it shows same result"? There might be multiple entries that have the same creation date and if you omit a sort, Spring Data will by default sort by id to provide a consistent result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...