hibernate - 休眠查询命名参数中的单引号给出错误
问题描述
我需要在 timeBucket 周围有一个单引号。我有以下本机 sql,它工作得很好。
entityManager.createNativeQuery("SELECT time_bucket('" + timeBucket + "', time) as timestamp, avg(cast(value as double precision)) as value" +
" FROM agent_data " +
" WHERE agent_id = :agentId and topic_id = :topicId" +
" GROUP BY timestamp " +
" ORDER BY timestamp DESC " +
" LIMIT :noOfRecords", "GetAgentDataMapping")
.setParameter("noOfRecords", noOfRecords)
.setParameter("agentId", agentId)
.setParameter("topicId", topicId)
.getResultList();
我正在连接 timeBukcket 参数,因为如果我使用 setParameter 方法绑定该变量,则会出现错误
"Could not locate ordinal parameter [1], expecting one of [2, 3, 4, 5, 6]; nested exception is java.lang.IllegalArgumentException: Could not locate ordinal parameter [1], expecting one of [2, 3, 4, 5, 6]"
我尝试使用 sql 字符串连接,如下所示。但它失败并出现同样的错误:
em.createNativeQuery("SELECT time_bucket('|| :timeBucket ||', time) as timestamp, avg(cast(value as double precision)) as value" +
" FROM agent_data " +
" WHERE agent_id = :agentId and topic_id = :topicId" +
" GROUP BY timestamp " +
" ORDER BY timestamp DESC " +
" LIMIT :noOfRecords", "GetAgentDataMapping")
.setParameter("timeBucket", timeBucket)
.setParameter("noOfRecords", noOfRecords)
.setParameter("agentId", agentId)
.setParameter("topicId", topicId)
.getResultList();
我也曾经SELECT time_bucket('''|| :timeBucket ||''', time)
转义单引号。
但是同样的错误,没有用。令人沮丧的是,Hibernate 没有针对如此简单的事情的快速解决方案。任何建议都会有所帮助。
解决方案
我想你正在使用时间刻度?使用以下内容有什么问题?
em.createNativeQuery("SELECT time_bucket(:timeBucket, time) as timestamp, avg(cast(value as double precision)) as value" +
" FROM agent_data " +
" WHERE agent_id = :agentId and topic_id = :topicId" +
" GROUP BY timestamp " +
" ORDER BY timestamp DESC " +
" LIMIT :noOfRecords", "GetAgentDataMapping")
.setParameter("timeBucket", timeBucket)
.setParameter("noOfRecords", noOfRecords)
.setParameter("agentId", agentId)
.setParameter("topicId", topicId)
.getResultList();
AFAIU 参数time_bucket
需要是字符串或区间。也许您需要将参数转换为间隔cast(:timeBucket as interval)
推荐阅读
- bash - 如何将范围保存到变量中以便稍后在 for 循环中使用它
- qt - 同一物业的不同价值
- python - 无法使用 Tableau Server 客户端 (TSC-Python) 连接到 Tableau Server
- node.js - 获取数据到 index.js(modul.export)
- c# - 如何使用 self-contained=false 从源创建 MSIX pckage
- javascript - 检查 typeof graphql 返回的数据
- python-3.x - 熊猫每天在特定时间范围内重新采样
- jestjs - 如何将 react-intl 与 jest 一起使用
- javascript - npm 包 @types/express 和 express 有什么区别
- java - 改造在查询参数中添加随机数?