(…) क्वेरी में एक HQL लिखने का उचित तरीका


80

यह मानते हुए कि मैं निम्नलिखित HQL क्वेरी लिखना चाहता हूं:

FROM Cat c WHERE c.id IN (1,2,3)

what is the proper way of writing this as a parametrized query, e.g.

FROM Cat c WHERE c.id IN (?)

जवाबों:


130

I am unsure how to do this with positional parameter, but if you can use named parameters instead of positional, then named parameter can be placed inside brackets and setParameterList method from Query interface can be used to bind the list of values to this parameter.

...
Query query = session.createQuery("FROM Cat c WHERE c.id IN (:ids)");
query.setParameterList("ids", listOfIds);
...

11

Older versions of Hibernate may not have the setParameterList method on Query. You can still call setParameter("ids", listOfIds); on the older one for the same effect.


5
Why has this been changed anyways? Just spent an hour figuring out why IllegalArgumentException in class: org.ase.mip.persistence.entities.BaseEntityImpl, getter method of property: id (BasicPropertyAccessor.java:186)) was happening. I called setParameter instead of setParameterList. DOH!
opncow

-4

Named parameters are better than positional parameters, we should be careful in looking at the order/position - while named is easy.

Named:

Query query = session.createQuery("select count(*) from User"+" where userName=:userName and passWord=:passWord");
        query.setString("userName", userName);
        query.setString("passWord", passWord);

Positional:

Query query=em.createQuery("SELECT e FROM Employee e WHERE e.empId = ? and  e.empDepartment = ?");
query.setParameter(1, employeId);
query.setParameter(2, empDepartment);

3
Fully agree, but that does not answer my question about IN(...) queries
Robert Munteanu
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.