使用 JPA 按嵌套 属性 排序时结合 DISTINCT 和 ORDER BY

Combining DISTINCT and ORDER BY when ordering by nested property with JPA

我有一个 JPQL 查询,它正在寻找具有可分页功能的不同记录。在某些情况下,可分页排序将是嵌套 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);
}

如果我按 entity2 调用查询排序,则会返回正确的结果。但是,当我尝试按 entity2.fieldToSort 排序时,出现以下错误:

ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

如果我删除 DISTINCT 限制,查询运行正常,但是 returns 每个 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);