Hibernate createNativeQuery using IN clause

5.8k Views Asked by At

Using Java, Hibernate.

I have a query

String pixIds = "1,2,3";
String query = "SELECT * FROM comment WHERE PIX_ID IN (:pixIds)";
q.setParameter("pixIds", pixIds);
List<Object[]> results =  q.getResultList();

I'm not able to bind this parameter to pixIds using the code above. What is the right way to do this?

Note : the query I have here is a simplified version of my actual query.

2

There are 2 best solutions below

1
On BEST ANSWER

The following method works
public Query setParameterList(String name, Collection vals) throws HibernateException

4
On

Hibernate doesn't support binding collection to IN (...) in SQL queries.

You need to work the same way as with plain JDBC: given a collection, dynamically generate a query with appropriate number of ?s in IN clause, and then bind elements of that collection to ?s.