Hibernate: How do I rewrite this criteria to HQL?
I want to write HQL, where I find out if Company has Persons(employees) with some of given names. I've managed to do that with criteria:
public List<Person> namesInCompany(Company company, Session session,
String... names) {
return session.createCriteria(Person.class)
.add(Restrictions.in("name", names))
.add(Restrictions.eq("company", company))
.list();
}
Now, I'd like same for HQL. I am using named queries, but I am having trouble how to pass array or list of strings (or anything) as parameter for named query. Here's my attempt, that doesn't work atm.
<query name="namesInCompany">
<query-param name="company" type="sk.xorty.task.Company"/>
<query-param name="names" type="java.util.List"/>
<![CDATA[
from Person p
where p.company = :company
and p.name in (:names)
]]>
</query>
I'm getting ClassCastException
java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
at org.hibernate.type.descriptor.java.StringTypeDescriptor.unwrap(StringTypeDescriptor.java:40)
That is normal, because I specified wrong type for query-param names. I don't know what to put there :/
Test case for better understanding of this开发者_如何学运维 service:
assertTrue (2 == service.namesInCompany(someCompany, session, "jon", "josh").size());
That means, that either "jon" or "josh" work at someCompany.
Thanks for help
EDIT
JB Nizet proposed code for service.namesInCompany. Here it is:
public List<Person> namesInCompany(Company company, Session session,
String... names) {
Query namesInCompany = session.getNamedQuery(
"sk.xorty.task.Person.namesInCompany");
namesInCompany.setParameter("company", company);
namesInCompany.setParameter("names", names);
return namesInCompany.list();
}
You have two problems:
- You declare the parameter as
java.util.List
, but you pass an array of Strings (a varargs argument is in fact an array) - You must use
setParameterList
, and notsetParameter
, to pass a collection of values.
精彩评论