【问题标题】:Combining DISTINCT and ORDER BY when ordering by nested property with JPA使用 JPA 按嵌套属性排序时结合 DISTINCT 和 ORDER BY
【发布时间】:2021-11-28 14:50:37
【问题描述】:

我有一个 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 记录。

当每个主要实体都需要不同的记录时,按子字段排序的最佳方式是什么?

【问题讨论】:

    标签: java spring-data-jpa jpql


    【解决方案1】:

    通过在存储库中使用嵌套查询解决了这个问题:

    @Query("select e1 from Entity1 e1 where e1 in (select e1 from Entity1 e1 left join e1.entity2 e2)")
    Page<Entity1> findDistinctCustom(Pageable pageable);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-08
      • 2011-09-13
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多