【发布时间】:2023-03-17 19:19:02
【问题描述】:
我有一个与自身有 1:n 关系的实体:
@Entity
@Table(name = "\"group\"")
class Group {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Integer id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "parentGroup")
@JoinTable(
inverseJoinColumns = {@JoinColumn(name = "parentgroup_id", referencedColumnName = "id", updatable = false)}
)
@OrderColumn
List<Group> groups = new ArrayList<>();
}
如果我使用 JPA 查询
select g from Group g where g.id = ?
我得到子组的有序列表。
如何获取父组的有序列表,以便以下查询返回所有没有父组的组的有序列表?
select g from Group g where g.parentGroup is null
我知道不可能为此使用 JPA。
我不想破坏我当前子组的顺序,如果我决定发明一个我自己填写的新列,就会发生这种情况。
我想订购父组,可能使用 JPA 为子组生成的现有列“groups_order”。
这个问题有精简的解决方案吗?
如果重要的话,我正在使用 JPA 2 和 EclipseLink 和 Spring Data JPA。
【问题讨论】:
-
您可以在第二个查询中使用 ORDER BY g.someProp
-
但这将包括使用自定义属性进行手动排序,这是我不想要的,因为它与我们订购子组的方式不同。
-
好吧,如果没有提供订购信息,该列表应该如何订购?您要么需要为 JPA 提供一些排序依据,要么“手动”对结果列表进行排序。
-
感谢您的建议,我(希望)澄清了我的要求。
-
用于父子关系的order字段是join表中的stores,反正因为parentGroup为null,这些group反正是没有ordering的。只需在组 id 字段上使用 order by。
标签: jpa eclipselink spring-data-jpa