[英]Combining DISTINCT and ORDER BY when ordering by nested property with JPA
我有一個 JPQL 查詢,它正在尋找具有可分頁的不同記錄。 在某些情況下,可分頁排序將成為嵌套類中的一個屬性。
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);
}
如果我按entity2
調用查詢排序,則會返回正確的結果。 但是,當我嘗試按entity2.fieldToSort
排序時,出現以下錯誤:
ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
如果我刪除DISTINCT
限制,查詢運行良好,但為每個Entity2
返回一個Entity1
記錄。
當需要每個主要實體的不同記錄時,按子字段處理排序的最佳方法是什么?
通過在存儲庫中使用嵌套查詢解決了這個問題:
@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.