[英]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.