Proper way of writing a HQL in ( ... ) query

HibernateHql

Hibernate Problem Overview


Assuming that I want to write the following HQL query:

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

Hibernate Solutions


Solution 1 - Hibernate

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);
...

Solution 2 - Hibernate

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.

Solution 3 - Hibernate

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobert MunteanuView Question on Stackoverflow
Solution 1 - HibernateMatejView Answer on Stackoverflow
Solution 2 - HibernateTravisView Answer on Stackoverflow
Solution 3 - HibernateMittinti Ramana MurthyView Answer on Stackoverflow