简体   繁体   中英

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()

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. 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.
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; secondly by using one of the following techniques:

  1. Use reflection to interrogate the type of your parameters and then use setParameter or setParameterList method accordingly.

  2. Use the benefits of polymorphism to capture parameters that are List objects and call setParameterList for those. Example below.*

  3. Make a big conditional block that tests casting to a bunch of list types and if it casts then call setParameterList, otherwise call setParameter.

(*) Example for approach 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM