【问题标题】:Sort query using Pageable with fields that is not in Select clause使用 Pageable 对不在 Select 子句中的字段进行排序查询
【发布时间】:2021-12-26 14:22:29
【问题描述】:

所以我的存储库中有这段代码(示例):

@Query("SELECT distinct s FROM Model1 ss LEFT JOIN ss.model2 s "
Page<Model2> methodName(long customerId, Pageable pageable);

Model1 我有一个字段 LocalDate lastDate。 如果我按 Model2 中的字段排序(使用 Pageable),则代码执行正常 但如果我需要按 model1 字段排序(例如按 lastDate),我会收到错误“无法解析属性”。如果我在“选择”中添加此字段,我也会收到错误“无法转换为 Model2 类”。我能为它做些什么?我不想添加“Order by”子句,也不想将此字段“lastDate”添加到Model1。有没有其他方法可以解决这个问题?

附言 可分页对象使用以下方法签名指定:

public PageRequest(int page, int size, Direction direction, String... properties)

【问题讨论】:

    标签: java hibernate jpa spring-data-jpa spring-data


    【解决方案1】:

    你不能。

    您返回的是Model2,它没有关于lastDate 的信息,那么JPA 怎么知道?

    您也不能将其添加到您的 SELECT 语句中,因为返回实体的类型为 Model2,这又不理解 lastDate

    您的 Model2 需要了解 lastDate 才能对其进行排序/分页。

    在 JPA 中,为了能够按特定字段排序,该字段必须是 select 语句中返回的实体的一部分。您无法使用未返回的属性进行排序

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 2017-11-14
      • 2019-12-15
      • 1970-01-01
      • 2020-09-19
      相关资源
      最近更新 更多