Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IN-clause in HQL or Java Persistence Query Language

I have the following parametrised JPA, or Hibernate, query:

SELECT entity FROM Entity entity WHERE name IN (?) 

I want to pass the parameter as an ArrayList<String>, is this possible? Hibernate current tells me, that

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String 

Is this possible at all?

ANSWER: Collections as parameters only work with named parameters like ":name", not with JDBC style parameters like "?".

like image 894
Daniel Avatar asked Jan 28 '11 12:01

Daniel


People also ask

What is HQL query in Java?

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.

How do you write or condition in HQL query?

The easiest way is to either create the hql string based on the value (if subServiceId is existent or not) or use the criteria api, thus you will just have to add one extra equals filter in case of subServiceId presence. The question should be changed on how to add dynamic conditions to hql based on variable presence.

What is HQL Hibernate Query Language )?

Hibernate Query Language (HQL) is an easy to learn and powerful query language designed as an object-oriented extension to SQL that bridges the gap between the object-oriented systems and relational databases. The HQL syntax is very similar to the SQL syntax.

Is subquery supported in HQL?

Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed. Note that HQL subqueries can occur only in the select or where clauses. Note that subqueries can also utilize row value constructor syntax.


2 Answers

Are you using Hibernate's Query object, or JPA? For JPA, it should work fine:

String jpql = "from A where name in (:names)"; Query q = em.createQuery(jpql); q.setParameter("names", l); 

For Hibernate's, you'll need to use the setParameterList:

String hql = "from A where name in (:names)"; Query q = s.createQuery(hql); q.setParameterList("names", l); 
like image 104
jpkrohling Avatar answered Oct 18 '22 23:10

jpkrohling


in HQL you can use query parameter and set Collection with setParameterList method.

    Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");     q.setParameterList("names", names); 
like image 30
michal.kreuzman Avatar answered Oct 19 '22 01:10

michal.kreuzman