【问题标题】:Spring JPA - Issue while sorting on non entity columnSpring JPA - 在非实体列上排序时出现问题
【发布时间】:2019-10-14 07:09:06
【问题描述】:

我有一个要求,我需要通过分页来获取基于三个表的连接的记录(也有附加要求)。所以我写了一个 nativeQuery 来获取记录。以下是示例查询

@Query(value = "SELECT "
        + "a.GROUP_REF_ID as refId "
        + "count(case when c.STAT_CD in :userStatus then (c.grp_user_id) end) as numberOfUsers, "
        + "count(case when b.STAT_CD in :itemStatus then (b.grp_item_id) end) as numberOfItems  "
        + "from grp a left join grp_item b on a.grp_id=b.grp_id left join grp_user c on a.grp_id=c.grp_id "
        + "where a.stat_cd in :status and a.co_id in :cids "
        + "group by a.GROUP_REF_ID,a.grp_nam,a.GRP_DESC,a.co_id,a.co_nam,a.CRTE_BY, "
        + "a.CRTE_DT,a.UPDT_BY,a.UPDT_DT ", countQuery = "select count(*) from grp where stat_cd in :status and co_id in :cids ", nativeQuery = true)
public Page<Object> findByStatusAndCompanyIdIn(@Param("status") String status, @Param("cids") List<Long> companyIds,
        @Param("userStatus") List<GroupUserStatus> userStatus,
        @Param("itemStatus") List<GroupItemStatus> itemStatus, Pageable pageable);

现在还要求这些记录在选择部分的任何列上进行排序。因此,如果用户通过numberOfItems,记录将在其上进行排序。但是我在这里遇到了一个问题,因为如果我将Sort 参数作为numberOfItems 传递,spring 会在numberOfItems 之前添加一个a.,这会导致not able to find a.numberOfItems 出现错误。

有没有办法可以阻止 spring 在使用 Sort 创建查询时添加表别名,或者我应该用不同的方法编写我的逻辑

【问题讨论】:

  • 您已经非常接近 Spring Data 能够处理的极限了。您可以尝试将整个选择包装在另一个中:select * from (&lt;your current select) x
  • 这就是我最终所做的:)

标签: spring spring-boot spring-data-jpa spring-data


【解决方案1】:

让我的评论成为答案,以便可以将问题标记为已回答:

将整个选择包装在另一个中:select * from (&lt;your current select&gt;) x

【讨论】:

    【解决方案2】:

    我通过创建投影解决了这个问题。 (使用了 Kotlin,但你会明白要点的。)

    class ShowRepository : JpaRepository<Int, Show> {
        @Query("SELECT s AS show, (CASE WHEN (s.status = 'scheduled') THEN s.scheduledStartTime ELSE s.startTime END) AS time FROM Show s")
        fun findShows(pageable: Pageable): Page<ShowWithTime>
    }
    
    interface ShowWithTime {
        val show: Show,
        val time: Date?
    }
    

    这让 Spring-Data 发挥其全部魔力,使用 Sort.by(Order.desc("time")) 就像一个魅力。

    我在这里写了一些更详细的内容:Sorting by a Non-Entity Field

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2023-03-28
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      相关资源
      最近更新 更多