[英]Hibernate setting parameters in named query
I am trying to write a generic method that can pick up a named query, set the named parameters in it and return a result. 我正在尝试编写一个通用方法,该方法可以提取命名查询,在其中设置命名参数并返回结果。
The method looks like the following, 该方法如下所示:
s = getSession();
q = s.getNamedQuery(nameOfTheQuery);
keySet = queryParams.keySet();
itr = keySet.iterator();
while(itr.hasNext()){
key = itr.next();
//Problem here
q.setParameter(key, queryParams.get(key));
}
q.setMaxResults(maxResults);
q.setFetchSize(fetchSize);
log.info("::>>>> Query result :"+(q.uniqueResult()));
I am trying to set the named parameters to values here. 我正在尝试将命名参数设置为此处的值。 But when the parameter here happens to be a list or collection I get a
ClassCastException
while the q.uniqueResult()
但是当这里的参数恰好是列表或集合时,我会收到一个
ClassCastException
而q.uniqueResult()
Is there a way I can write this method to support collections and other types of parameters as well? 有没有一种方法可以编写此方法来支持集合和其他类型的参数? It is mandatory that I set the maxResults and fetchSize so I had to choose this option.
我必须设置maxResults和fetchSize,因此必须选择此选项。 Any help would be greatly appreciated.
任何帮助将不胜感激。 Thanks!
谢谢!
If I understand your question correctly. 如果我正确理解您的问题。
In my case I often use q.getResultList to get the collection of the result. 就我而言,我经常使用q.getResultList来获取结果的集合。
I think this may help you to find the solution. 我认为这可以帮助您找到解决方案。
您需要使用setParameterList(key,value),其中vale是您的列表。
I suspect the answer to your question is firstly to use the setParameterList
method when the parameter is a list type; 我怀疑您的问题的答案是,当参数为列表类型时,首先使用
setParameterList
方法。 secondly by using one of the following techniques: 其次,使用以下技术之一:
Use reflection to interrogate the type of your parameters and then use setParameter or setParameterList method accordingly. 使用反射来询问参数的类型,然后相应地使用setParameter或setParameterList方法。
Use the benefits of polymorphism to capture parameters that are List objects and call setParameterList for those. 利用多态的好处来捕获作为List对象的参数,并为其调用setParameterList。 Example below.*
下面的示例。*
Make a big conditional block that tests casting to a bunch of list types and if it casts then call setParameterList, otherwise call setParameter. 制作一个大的条件块来测试是否转换为一堆列表类型,如果转换,则调用setParameterList,否则调用setParameter。
(*) Example for approach 2. (*)方法2的示例
while(itr.hasNext())
{
key = itr.next();
QueryParameterHelper.setGenericParameter(q, key, queryParams.get(key));
}
public static class QueryParameterHelper
{
public static void setGenericParameter(Query query, String paramName, List listValue)
{
query.setParameterList(paramName, listValue);
}
public static void setGenericParameter(Query query, String paramName, String stringValue)
{
query.setParameter(paramName, stringValue);
}
//etc for other possible parameter types
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.