我正在尝试通过使用“:”字符的JPA运行本机查询.特定实例在查询中使用MySQL用户变量:
SELECT foo, bar, baz,
@rownum:= if (@id = foo, @rownum+1, 1) as rownum,
@id := foo as rep_id
FROM
foo_table
ORDER BY
foo,
bar desc
JPA代码:
Query q = getEntityManager().createNativeQuery(query, SomeClass.class);
return q.getResultList();
但是,这给了我一个例外,即不允许用空格跟随’:’.我已经尝试用反斜杠逃避它们,我已经尝试通过将它们加倍来逃避它们.有没有办法真正做到这一点,还是我是SOL?
解决方法:
我不知道在查询中转义冒号字符的标准方法,该查询显然被解释为命名参数前缀,从而混淆了查询解析器.
我的建议是尽可能创建和使用SQL函数.根据您的提供程序,可能还有其他选项(例如使用另一个字符并用拦截器代替所选字符)但至少先前的建议会使您的JPA代码在提供程序之间保持可移植性.
PS:如果你正在使用Hibernate,那么HHH-1237附带了一个非常旧的补丁.
更新:JPA 1.0规范中有一个关于命名参数和本机查询的“有趣”段落:
3.6.3 Named Parameters
A named parameter is an identifier
that is prefixed by the “:” symbol.
Named parameters are case-sensitive.
Named parameters follow the rules for
identifiers defined in Section 4.4.1.
The use of named parameters applies to the Java Persistence query
language, and is not defined for
native queries. Only positional
parameter binding may be portably used
for native queries.
The parameter names passed to the
setParameter methods of the Query
API do not include the “:” prefix.
这对你没有用,但是你的情况强烈暗示原生查询中的“:”甚至不应该被考虑(至少没有办法逃脱它或禁用它检测).
标签:mysql,jpa,jpql
来源: https://codeday.me/bug/20191001/1838361.html