[英]Combining DISTINCT and ORDER BY when ordering by nested property with JPA
I have a JPQL query that is looking for distinct records with pageable.我有一个 JPQL 查询,它正在寻找具有可分页的不同记录。 There are situations where the pageable sort will be a property in a nested class.
在某些情况下,可分页排序将成为嵌套类中的一个属性。
public class Entity1 {
@Id
private long id;
@ManyToOne
private Entity2 entity2;
}
public class Entity2 {
@Id
private long id;
private String fieldToSort;
}
public interface Entity1Repository extends JpaRepository<Entity1, Long> {
Page<Entity1> findDistinct(Pageable pageable);
}
If I call the query sorting by entity2
, the correct result is returned.如果我按
entity2
调用查询排序,则会返回正确的结果。 However, when I try and sort by by entity2.fieldToSort
, I get the following error:但是,当我尝试按
entity2.fieldToSort
排序时,出现以下错误:
ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
If I remove the DISTINCT
restriction, the query runs fine, but returns an Entity1
record for each Entity2
.如果我删除
DISTINCT
限制,查询运行良好,但为每个Entity2
返回一个Entity1
记录。
What is the best way of handling sorting by sub fields, when requiring a distinct record for each of the main entities?当需要每个主要实体的不同记录时,按子字段处理排序的最佳方法是什么?
Solved this by using a nested query in the respository:通过在存储库中使用嵌套查询解决了这个问题:
@Query("select e1 from Entity1 e1 where e1 in (select e1 from Entity1 e1 left join e1.entity2 e2)")
Page<Entity1> findDistinctCustom(Pageable pageable);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.