使用jpa order by 错误的表名 Unknown column ‘XX.id‘ in ‘order clause Spring Data sorting on wrong Table

项目场景:

使用jpa在做复杂的关联查询的时候,使用sort排序,但orderby的字段,不是我想要的那张表


问题描述:

我原来的代码是这样的:

Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = new OffsetBasedPageRequest(offset, limit,sort);// 这个OffsetBasedPageRequest是jpa实现使用偏移量来查询数据的方法。
scanResultDatas = scanResultDataRespository.findAllByScanResultIdGroupBy(scanResultId,scanJobId,pageable);


// 这是我respository 代码


@Query(value = "select *,IF((select count(1) as num from whitelist_data a where a.scan_job_id = ?2  AND (a.index_colname = b.index_colname AND a.database_path = b.database_path))>0,1,0) as include from scan_result_data b where b.scan_result_id = ?1 GROUP BY database_path,index_colname \n#pageable\n",
            countQuery = "select count(*),IF((select count(1) as num from whitelist_data a where a.scan_job_id = ?2  AND (a.index_colname = b.index_colname AND a.database_path = b.database_path))>0,1,0) as include  from scan_result_data b where b.scan_result_id = ?1 GROUP BY database_path,index_colname",
            nativeQuery = true)
Page<ScanResultDataEntity> findAllByScanResultIdGroupBy(long scanResultId,long scanJobId, Pageable pageable);


报错如下:Unknown column 'a.id' in 'order clause'
// 

我想要的效果:

........... order by b.id

实际上jpa拼装出来的是:

........... ORDER BY a.id

原因分析:

说实话,我没有找到原因是什么,同样的,我好像很少有人和我有这样一样的问题。和我遇到一样问题的人:https://stackoverflow.com/questions/30387371/spring-data-sorting-on-wrong-table?answertab=oldest#tab-top


解决方案:

将pageable的sort去掉,自己在sql里实现orderby的功能,
修改后:


//Sort sort = new Sort(Sort.Direction.DESC, "id");
// 不用jpa的sort的方法了
Pageable pageable = new OffsetBasedPageRequest(offset, limit); 

@Query(value = "select *,IF((select count(1) as num from whitelist_data a where a.scan_job_id = ?2  AND (a.index_colname = b.index_colname AND a.database_path = b.database_path))>0,1,0) as include from scan_result_data b where b.scan_result_id = ?1 GROUP BY database_path,index_colname order by id desc \n#pageable\n",
            countQuery = "select count(*),IF((select count(1) as num from whitelist_data a where a.scan_job_id = ?2  AND (a.index_colname = b.index_colname AND a.database_path = b.database_path))>0,1,0) as include  from scan_result_data b where b.scan_result_id = ?1 GROUP BY database_path,index_colname",
            nativeQuery = true)
Page<ScanResultDataEntity> findAllByScanResultIdGroupBy(long scanResultId,long scanJobId, Pageable pageable);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值