【问题标题】:Default sorting on CrudRepository?CrudRepository 上的默认排序?
【发布时间】:2018-07-18 15:43:29
【问题描述】:

是否可以为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 注释或类似的)。

【问题讨论】:

  • 你是否在 Hibernate 中使用 Spring 数据?
  • 是的,我正在使用spring-boot 提供的完整堆栈,包括休眠映射。
  • @membersound, @SortDefault 没有应用于方法,或者我错过了什么?
  • 好吧,把它扔在那里:如果你只是根据需要传递你的排序,你总是可以只实现该接口来拥有该存储库的自定义实现,但调用它的方法将没有 @ 987654328@ 位。我知道,也许不是我们想要的
  • @AndrewTobilko 当然不是,这就是为什么我在后面的评论中写了“这是无效的”;)

标签: java spring hibernate spring-data


【解决方案1】:

您可以在您的 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;
}

例如,此技巧将实体的lastname 字段的默认升序应用到findAll metthed。

更新

另一个没有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);

【讨论】:

  • 没有Pageable也一样可以,所以方法调用根本不需要提供参数?
  • @membersound 我更新了答案 - 可能这个变体会有所帮助......
  • 好的,对于已经存在的findAll() 接口,这可能会起作用。但是我最初的问题中使用的方法,比如findAllByAge()
  • spring 1.5.x 有类似的解决方案吗?不幸的是,Sort.by() 是 spring 2.x 方法..
  • @membersound new Sort(...)
【解决方案2】:

这将是一个非常酷的功能!
根据您的数据库,返回的订单可能不是what you expect™。例如,PostgreSQL 似乎不是按 PrimaryKey 上的 asc/desc 排序,而是按 lastModified 排序。

目前没有为代理/虚拟(存储库接口定义)方法(findByXYZ)提供默认排序顺序的“间接”解决方案。

您唯一的选择是通过提供一个排序对象来明确指定它

Sort.by("id"); //default is ASC
Sort.by(Sort.Order.desc("id"));
Sort sort = Sort.by("id").descending();
repo.findAll(sort);

或在您的存储库界面中相应地命名自定义查询方法:

public interface YourEntityRepository extends JpaRepository<YourEntity, Long> {
        List<Entit> findAllByOrderById();
}

(请注意必要的额外“By”,即使没有给出“where”子句)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2011-04-13
    • 1970-01-01
    • 2012-06-01
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多