spring-projects / spring-data-commons

Spring Data Commons. Interfaces and code shared between the various datastore specific implementations.
https://spring.io/projects/spring-data
Apache License 2.0
778 stars 675 forks source link

Add sorting ability for unpaged request in QuerydslPredicateExecutor [DATACMNS-1405] #1840

Open spring-projects-issues opened 6 years ago

spring-projects-issues commented 6 years ago

Vladyslav Tkachuk opened DATACMNS-1405 and commented

I'm sorry for a bit confusing title, but I'll try to explain it here.

So, org.springframework.data.querydsl.QuerydslPredicateExecutor has a method to return paged data Page findAll(Predicate predicate, Pageable pageable).

If you want to get all existing entities as one page, Pageable.unpaged() as a second paramater.

However, this way you cannot get this single page sorted anyhow, whereas QPageRequest and PageRequest which extend AbstractPageRequest which implements Pageable have sorting ability.

Based on this, if you want to have a single page with all entities, you won't get it sorted.

To my mind this functionality is missing. 

I would be interested to hear your opinions and ideas.

 


No further details from DATACMNS-1405

spring-projects-issues commented 4 years ago

Oskars Pakers commented

This would be very beneficial to apply default sorting when pagination is not used (but can be passed). A simple class can be added.

class UnpagedSorted implements Pageable {
    private final Sort sort;

    UnpagedSorted(Sort sort) {
        this.sort = sort;
    }

    public boolean isPaged() {
        return false;
    }

    public Pageable previousOrFirst() {
        return this;
    }

    public Pageable next() {
        return this;
    }

    public boolean hasPrevious() {
        return false;
    }

    public Sort getSort() {
        return sort;
    }

    public int getPageSize() {
        throw new UnsupportedOperationException();
    }

    public int getPageNumber() {
        throw new UnsupportedOperationException();
    }

    public long getOffset() {
        throw new UnsupportedOperationException();
    }

    public Pageable first() {
        return this;
    }
}

Then service method can use the same repository method, for example.

if (limit == null) {
    return songRepository.findByArtist(artist, new UnpagedSorted(Sort.by("title").ascending()));
}
return songRepository.findByArtist(artist, PageRequest.of(0, limit)); 

What do you think? If this is ok, I could submit a pull request