Java 将列表参数设置为本机查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18701946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set list parameter to native query
提问by Silence
I would like to set parameter to a native query,
我想将参数设置为本机查询,
javax.persistence.EntityManager.createNativeQuery
Something like that
类似的东西
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter(1, paramList);
Trying this query result in Exception:
在异常中尝试此查询结果:
Caused by: org.eclipse.persistence.exceptions.DatabaseException:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near
'_binary'?? Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
List<String> paramList = new ArrayList<String>();
String queryParams = null;
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter(1, paramList);
Iterator<String> iter = paramList.iterator();
int i =0;
while(iter.hasNext(){
if(i != paramList.size()){
queryParams = queryParams+ iter.next() + ",";
}else{
queryParams = queryParams+ iter.next();
}
i++;
}
query.setParameter(1, queryParams );
?srQuery query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN (:names)");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter("names", paramList);
?java.util.ArrayListx?????a??##代码##?I##代码##?sizexp##代码####代码####代码##?w?##代码####代码####代码##t##代码##
f' at line 1
Error Code: 1064
Call: SELECT * FROM Client a WHERE a.name IN ?
bind => [[firstValue, secondValue]]
Query: ReadAllQuery(referenceClass=TABLE_A sql="SELECT * FROM TABLE_A a WHERE a.name IN ?")
Is it any way to set list parameter for native query, without cast to string and append it to sql query?
有没有办法为本机查询设置列表参数,而无需转换为字符串并将其附加到 sql 查询?
P.S. I'm use EclipseLink 2.5.0 and MySQL server 5.6.13
PS 我使用 EclipseLink 2.5.0 和 MySQL 服务器 5.6.13
Thanks
谢谢
采纳答案by James
I believe you can only set list parameters to JPQL queries, not native queries.
我相信您只能将列表参数设置为 JPQL 查询,而不是本机查询。
Either use JPQL, or construct the SQL dynamically with the list.
要么使用 JPQL,要么使用列表动态构建 SQL。
回答by Ryan Marken
Not a solution but more of a workaround.
不是解决方案,而是更多的解决方法。
##代码##回答by UnixShadow
It works if you name the parameter:
如果您命名参数,它会起作用:
##代码##