Search code examples
sqlhibernatehql

change positional parameters to named parameters in HQL


I am upgrading hiberate to 5 now and need to change all position parameters (removed in 5) to named parameters. I have a question for how to use named parameters in "mutiple ? in in-clause". For example, I have a query

select people from users where grade in ( ?, ?, ?, ?.......

I do not know the exact numbers of "?" in the HQL query. With the positional parameters, I can simply

   int index = 0;
   for(Grade g : GradeList) {
      query.setParameter(index++, g);
    }

so "index" can help me dynamically generate the index position in the HQL query. If I want to replace this query with named parameters, how do we usually do it? Do we do someting like

String s = "p";
int index = 0;
for(Grade g : GradeList) {
  String ss = s + index++;
  query.setParameter("ss", g);
}

then what should I put into the query for "?". s1, s2, s3, s4???


Solution

  • If you're using org.hibernate.query.Query then

    String queryString = "select people from users where grade IN (:grades)";
    // Query query = session.createQuery (queryString);
    
    query.setParameterList("grades", gradeList);
    

    If you're using JPA then

    query.setParameter("grades", gradeList);