Spring Data中TypedSort 'by'按官方示例编译失败,求助排查原因
Hey there! Let's break down why you're hitting this compilation error with Spring Data's TypedSort.
First, let's unpack what's happening:
- The official docs show chaining
ascending().and(...)and assigning the result back to aTypedSort<Person>variable, but this fails in your OpenJDK 13 environment with a type mismatch error. - When you simplify the code to assign the result to a plain
Sortvariable, it works perfectly.
What's the Root Cause?
The issue comes down to a version mismatch between your Spring Data setup and the version the documentation was written for.
In older Spring Data releases, the by() method on TypedSort might have returned another TypedSort instance, letting you chain calls while retaining the type. But in newer versions (compatible with JDK 13 and later), the by() method returns a Sort.Order-related type, and subsequent calls like ascending() or and() resolve to a plain Sort object—not a TypedSort.
This makes the official example's assignment to TypedSort<Person> invalid, since the chained operation produces a Sort which can't be cast to TypedSort.
The Correct Approach for Your Version
Your simplified code is actually the right way to handle this for your Spring Data version:
TypedSort<Person> sorter = Sort.sort(Person.class); Sort sorted = sorter.by(Person::getFirstName).descending();
If you need to build a compound sort with multiple fields, you can still do it—just assign the final result to a Sort variable:
TypedSort<Person> sorter = Sort.sort(Person.class); Sort sorted = sorter.by(Person::getFirstName).ascending() .and(sorter.by(Person::getLastName).descending());
Is the Documentation Flawed?
Yes, it looks like the official documentation hasn't been updated to reflect the type changes in newer Spring Data versions. Documentation lagging behind code updates is a common hiccup in active projects like Spring Data, so this isn't a mistake on your part.
内容的提问来源于stack exchange,提问作者PaulN

