Java 休眠中的 setParameterList 如何工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9766479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does setParameterList in hibernate work?
提问by A Null Pointer
I am having some problem with the setParameterList api of hibernate.
我在使用 hibernate 的 setParameterList api 时遇到了一些问题。
I am trying to pass in a Collection to a SQLQuery and doing an "in" clause search.The records exists in the DB and doing a raw query, I am able to retrieve them or if I just replace them in the same Hibernate SQL like emp.emp_name in ('Joe','John')
, I am able to get the desired result set. I am confused as to why would Hibernate fail to replace the Collection in place of the named parameter. Here is the code :
我正在尝试将集合传递给 SQLQuery 并执行“in”子句搜索。记录存在于数据库中并进行原始查询,我能够检索它们,或者如果我只是在相同的 Hibernate SQL 中替换它们emp.emp_name in ('Joe','John')
,我能够得到想要的结果集。我很困惑为什么 Hibernate 无法替换 Collection 来代替命名参数。这是代码:
session.createSQLQuery("select emp_id as id from emp where emp.emp_name in (:empNames)")
.addScalar("id",Hibernate.INTEGER)
.setParameterList("empNames",new String[]{"Joe","John"})
.list()
I have looked at the Hibernate Documentation for setParameterListbut I am not able to reason out this particular behavior.
我已经查看了 setParameterList的Hibernate 文档,但我无法推断出这种特殊行为。
采纳答案by Jon Skeet
I suspectthe problem is precisely becauseyou're using createSQLQuery
. The single parameter here needs to be changed into multiple parameters in the real SQL, but by using a "raw" query you're telling Hibernate not to mess with the SQL.
我怀疑问题正是因为您使用的是createSQLQuery
. 在真正的 SQL 中,这里的单个参数需要更改为多个参数,但是通过使用“原始”查询,您告诉 Hibernate 不要弄乱 SQL。
Can you use a "normal" Hibernate query instead?
您可以改用“普通”Hibernate 查询吗?
回答by biou_biou
Just remove the parenthesis around the parameter name :
只需删除参数名称周围的括号:
session.createSQLQuery("select emp_id as id from emp where emp.emp_name in :empNames ")
.addScalar("id",Hibernate.INTEGER)
.setParameterList("empNames",new String[]{"Joe","John"})
.list()
回答by DNQ
I would not suggest to use (N)Hibernate's parameter lists. Query plans in cache are not used when the number of elements in parameter list is different. So it means your query is often hard parsed and compiled. Queries are slower, database load is higher and plan cache is full of plans generated for the same query.
我不建议使用 (N)Hibernate 的参数列表。当参数列表中的元素数量不同时,不使用缓存中的查询计划。所以这意味着您的查询通常是硬解析和编译的。查询速度较慢,数据库负载较高,计划缓存中充满了为同一查询生成的计划。