Search code examples
javahibernatejpanamed-query

JPA @namedQuery with "IN" expression


Im having the following namedQuery:

@NamedQuery(name = Department.getDepartmentsByIds, query = "SELECT tbl FROM Department tbl where tbl.id in (:departmentsIds)") 

I would like to pass the parameter: departmentsIds = "1,2,3" like this:

query.setParameter("departmentsIds","1,2,3");

but i get an error:

java.lang.IllegalArgumentException: Parameter value [1,2,3] was not matching type [java.lang.Long]

any ideas why?


Solution

  • Pass a List to the setParameter method instead of a String. The generic type argument of List should correspond with the type of your departmentIds field.

    List<Integer> ids = new ArrayList<Integer>(); //this should be your id column's type
    ids.add(1);
    ids.add(2);
    ids.add(3);
    query.setParameter("departmentsIds",ids);