You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Data分页Oracle表别名报错ORA-00904,自动count查询失效

解决Spring Data JPA原生查询分页时Oracle的ORA-00904错误

问题出在Spring Data JPA自动生成的count查询上:它用了count(r),但Oracle不支持直接对表别名使用count(),必须指定具体列或者使用count(*)这类合法写法,这才触发了ORA-00904: "R" : invalid identifier错误。

解决办法

最稳妥的方式是手动指定countQuery,哪怕你的Spring Boot版本(2.7.1)理论上支持自动生成。修改后的Repository代码如下:

@Query(
    value = "select * from students r inner join conf c on r.status_id = c.id where c.code = 'NEW'",
    countQuery = "select count(r.id) from students r inner join conf c on r.status_id = c.id where c.code = 'NEW'",
    nativeQuery = true
)
Page<Student> findNewStudents(Pageable pageable);

你也可以把count(r.id)换成count(*),因为是inner join,两者统计结果一致,Oracle执行效率也差不多。

原因说明

Oracle的SQL语法中,count()函数的参数需要是列名、*或者合法的表达式,直接传入表别名(比如这里的r)会被识别为无效标识符。Spring Data JPA的自动count查询生成逻辑没有适配Oracle的这个特性,所以即使是高版本(2.4.3+)也会生成不符合Oracle语法的count语句。

内容的提问来源于stack exchange,提问作者hakima maarouf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:03:22