java SQLQuery 中的休眠命名参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32889465/
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
Hibernate Named Parameters in SQLQuery
提问by Viktor V.
Hibernate named parameters could not be inserted into SQL query:
无法将 Hibernate 命名参数插入到 SQL 查询中:
String values="'a', 'b', 'c', 'd'";
SQLQuery query = getSession().createSQLQuery("SELECT * FROM data WHERE value IN (:values)");
query.setParameter("values", values);
List<Object[]> data = query.list(); // returns data: size = 0 ...
However, if I will write:
但是,如果我会写:
String values="'a', 'b', 'c', 'd'";
SQLQuery query = getSession().createSQLQuery("SELECT * FROM data WHERE value IN (" + values + ")");
List<Object[]> data = query.list(); // returns data: size = 15 ...
Second way returns me data instead of first way.
第二种方式返回数据而不是第一种方式。
What I do wrong using named parameters in SQL?
在 SQL 中使用命名参数我做错了什么?
回答by Priyesh
The values
variable should be a list or an array of Strings, not a string, as the parameter is in an 'IN' clause.
So, change your code to the below and it should work:
该values
变量应该是一个列表或一个字符串数组,而不是字符串,作为参数处于“IN”子句。因此,将您的代码更改为以下内容,它应该可以工作:
String[] values= {"a", "b", "c", "d"};
SQLQuery query = getSession().createSQLQuery("SELECT * FROM data WHERE value IN (:values)");
query.setParameterList("values", values);
List<Object[]> data = query.list();
回答by Stanislav
Your second approach doesn't create a named parameter in the query, it just concatenates a string and you get a permanent query like it was made so:
您的第二种方法不会在查询中创建命名参数,它只是连接一个字符串,您会得到一个永久查询,就像这样:
SQLQuery query = getSession().createSQLQuery("SELECT * FROM data WHERE value IN ('a', 'b', 'c', 'd')");
To make the first one work with Hibernate, you have to pass an array or a collection of Objects, not a single string and use a setParameterList method. Just like:
要使第一个与 Hibernate 一起工作,您必须传递一个数组或一组对象,而不是单个字符串,并使用 setParameterList 方法。就像:
query.setParameterList("reportID", new Object[]{"a","b","c","d"});