2

我有一个要求,我需要通过分页来获取基于三个表的连接的记录(也有附加要求)。所以我写了一个 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 会在前面加上一个a.numberOfItems这会导致错误not able to find a.numberOfItems

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

4

2 回答 2

2

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

将整个选择包装在另一个中:select * from (<your current select>) x

于 2019-10-14T10:17:45.387 回答
0

我通过创建投影解决了这个问题。(使用了 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"))像魅力一样使用作品。

我在这里写了一些更详细的内容:按非实体字段排序

于 2020-03-21T21:47:03.003 回答