Proper way of writing a HQL in ( … ) query

不打扰是莪最后的温柔 提交于 2019-12-18 10:22:17

问题


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

回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/961816/proper-way-of-writing-a-hql-in-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!