简体   繁体   中英

How does setParameterList in hibernate work?

I am having some problem with the setParameterList api of hibernate.

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 :

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 setParameterList but I am not able to reason out this particular behavior.

I suspect the problem is precisely because you'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.

Can you use a "normal" Hibernate query instead?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM