HQL 或 Java 持久化查询语言中的 IN 子句

我有以下参数化 JPA 或 Hibernate 查询:

SELECT entity FROM Entity entity WHERE name IN (?)

我想把参数作为 ArrayList < String > 传递,这可能吗? Hibernate current 告诉我,

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

这有可能吗?

答案 : 作为参数的集合只能使用“ :name”这样的命名参数,而不能使用“ ?”这样的 JDBC 样式参数。

166690 次浏览

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

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

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

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

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