是否可以为 CrudRepository
添加默认排序方法?喜欢:
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;
}
与 findAllByAge(int age, Sort sort);
相反优点是不必提供 Sort
由每个调用类。
(旁注:我知道我可以将类重命名为 findAllByAgeSortLastnameAsc()
,但我明确询问 @SortDefault 注释或类似内容)。
最佳答案
您可以在存储库中使用以下技巧:
@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;
}
例如,此技巧将按实体的 lastname
字段的默认升序应用于 findAll
方法。
已更新
没有 Pageable
作为参数的另一个变体:
@Override
default List<Person> findAll() {
return findAll(Sort.by(Sort.Direction.ASC, "lastname"));
}
或者对于任意方法:
default List<Person> findAllByAge(int age) {
return findAllByAge(int age, Sort.by(Sort.Direction.ASC, "lastname"));
}
List<Person> findAllByAge(int age, Sort sort);
关于java - CrudRepository 上的默认排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406088/