IN-clause in HQL or Java Persistence Query Language

JavaHibernateJpaHqlJpql

Java Problem Overview


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 "?".

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.

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

Solution 4 - Java

Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:

Entity.java:

@Entity
@NamedQueries({
    @NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
    @Column(name = "attribute")
    private String attribute;
}

Dao.java:

public class Dao {
    public List<Entity> findByAttributes(Set<String> attributes) {
        Query query = em.createNamedQuery("byAttributes");
        query.setParameter(1, attributes);

        List<Entity> entities = query.getResultList();
        return entities;
    }
}

Solution 5 - Java

query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue

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
QuestionDanielView Question on Stackoverflow
Solution 1 - JavajpkrohlingView Answer on Stackoverflow
Solution 2 - Javamichal.kreuzmanView Answer on Stackoverflow
Solution 3 - JavaSteven SpunginView Answer on Stackoverflow
Solution 4 - JavaAttila TView Answer on Stackoverflow
Solution 5 - JavaShahid Hussain AbbasiView Answer on Stackoverflow