Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default sorting on CrudRepository?

Is it possible to add a default sorting to a CrudRepository method? Like:

interface PersonRepository extends CrudRepository<Person, Long> {
   @SortDefault(sort = "lastname", direction = Sort.Direction.ASC) //this is invalid
   List<Person> findAllByAge(int age);
}

@Entity
public class Person {
    @Id long id;
    String firstname, lastname;
    int age;
}

In contrast to findAllByAge(int age, Sort sort); the advantage would be not having to provide a Sort by each invoking class.

(sidenote: I know I could rename the class to findAllByAgeSortLastnameAsc(), but I'm explicit asking about @SortDefault annotation or similar).

like image 408
membersound Avatar asked Mar 20 '26 22:03

membersound


1 Answers

You can use the following trick in your repo:

@Override
default Page<Person> findAll(Pageable pageable) {
    return findAllBy(applyDefaultOrder(pageable));
}

Page<Person> findAllBy(Pageable pageable);

default Pageable applyDefaultOrder(Pageable pageable) {
    if (pageable.getSort().isUnsorted()) {
        Sort defaultSort = Sort.by("lastname").ascending();
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), defaultSort);
    }
    return pageable;
}

This trick for example apply default ascending order by lastname field of the entity to the findAll metthed.

UPDATED

Another variant without Pageable as parameter:

@Override
default List<Person> findAll() {
    return findAll(Sort.by(Sort.Direction.ASC, "lastname"));
}

Or for an arbitrary method:

default List<Person> findAllByAge(int age) { 
    return findAllByAge(int age, Sort.by(Sort.Direction.ASC, "lastname"));
} 

List<Person> findAllByAge(int age, Sort sort);
like image 127
Cepr0 Avatar answered Mar 24 '26 11:03

Cepr0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!