【问题标题】:Sorting entities by their @OneToMany relationship property with Spring Data JPA使用 Spring Data JPA 通过 @OneToMany 关系属性对实体进行排序
【发布时间】:2019-02-09 14:38:15
【问题描述】:

我正在开发使用 Spring Data JPA 作为其持久层的 Spring Boot Web 应用程序。从存储库中检索实体时,我使用 Spring 的 Data JPA Sort 对象对它们进行排序。当我按检索到的实体属性或其@OneToOne 关系对象属性进行排序时,它可以工作,但我想使用它按@OneToMany 关系对象属性之一进行排序。

让我们用一个例子来解释一下:假设我有一个实体对象Author,它与另一个实体Book有一对多的关系。我的最简单形式的实体类如下所示:

@Entity
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @OneToMany(mappedBy = "author")
    private List<Book> books;

    <constructor, getters, setters etc.>
}

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String title;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

    <constructor, getters, setters etc.>
}

现在,当我使用 Spring 的存储库接口检索作者时,我将 Sort 对象传递给它,如下所示:

new Sort(Sort.Direction.ASC, "id")

这给了我按作者 ID 升序排序的结果。我想传递这样的东西:

new Sort(Sort.Direction.ASC, "books.title")

假设我在数据库中有这些数据(简化表只是为了展示示例):

author  | book_title
---------------------
Andrew  | Letter C
Barbara | Letter A
Andrew  | Letter B
Barbara | Letter D

结果列表将是 Barbara(她的书“字母 A”在按书名排序后排在第一位)然后是 Andrew。

现在传递 new Sort(Sort.Direction.ASC, "books.title") 会得到“Barbara, Andrew, Andrew, Barbara” - 这意味着结果列表中有重复项 - 我希望结果不同。

想在 Author 的收藏中使用 @OrderBy,因为我对实际的图书订单不感兴趣 - 只有作者。

想使用 JPQL 在存储库级别使用 @Query 对结果进行排序(可能有一些 JPQL 子查询和虚拟字段可能),因为我需要它能够动态接受可排序的文件(它现在可能是标题,但在其他情况下是 isbn 编号,我的 API 应该能够采用其中一个)。

必须使用我用来过滤结果的 Spring Specification API。

有可能吗?

【问题讨论】:

  • 现在的结果是“Barbara, Andrew, Andrew, Barbara” - 预期的输出是什么?我认为输出涵盖了需求。
  • 我希望它与众不同,所以没有重复,只有 Barbara 然后 Andrew,在这种情况下这将是整个列表(也将此行添加到问题中)。
  • 我想这就是你所需要的 - findDistinctBy : stackoverflow.com/questions/48540789/…
  • 您可以在此处从给定线程中查看指向 Spring 的讨论:jira.spring.io/browse/DATAJPA-744
  • 您可以使用随意的findAll() 获取您的作者,然后使用重写的比较器将它们维护在 TreeSet 中。

标签: java sorting jpa spring-data-jpa


【解决方案1】:

我有同样的问题,但我找到了这个答案:

@OneToMany
@OrderBy("value ASC") // sort by value ASC
private List<PropertyDefinition> propertyDefinitions;

查看此链接中的答案: Spring Data JPA sorting on nested collection

它解决了我的问题。

【讨论】:

    猜你喜欢
    • 2019-10-25
    • 2022-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2019-04-26
    • 2018-10-11
    • 2021-05-22
    相关资源
    最近更新 更多