Search code examples
springsorting

TypedSort 'by' in Spring Data as described in reference docs does not compile


I am a newbie with Spring Data and I am trying to implement a TypeSort 'by'. The reference docs show the following example:

TypedSort<Person> person = Sort.sort(Person.class);
TypedSort<Person> sort = person.by(Person::getFirstname).ascending()
  .and(person.by(Person::getLastname).descending());

This does not compile on my computer (Type mismatch: cannot convert from Sort to Sort.TypedSort). I am using OpenJDK version 13. After some trying, the following code (a little bit simplified for testing) seems to work ok:

TypedSort<Person> sorter = Sort.sort(Person.class);
Sort sorted = sorter.by(Person::getFirstName).descending();

Did I miss something in the documentation or is this a documentation flaw?


Solution

  • It's an error in the reference documentation or something they forgot to implement.

    As soon as you call .ascending() or .descending(), it's a Sort and no longer a TypedSort.

    I guess TypedSort it was only tested/implemented to be used as a 'fluent' API:

    Sort sort = Sort.sort(Person.class)
      .by(Person::getAddress)
      .by(Address::getZipCode)
      .ascending()
      .and(...) 
    

    So the following should work, but it's not like in the documentation:

    TypedSort<Person> person = Sort.sort(Person.class);
    Sort sort = person.by(Person::getFirstname).ascending()
      .and(person.by(Person::getLastname).descending());
    repository.findAll(sort)