Search code examples
javasqljpql

JPQL SQL make a query base on a list of arguments


I have a class Person as followed

public class Person{
   String name;
   //----------
}

I would like to query the list of persons where name are like "name1" and name like "name2", and name like "name3" .... so, i would like to have a funtion like this

public void queryPersonsWhithNameLike(List<String>  names){
   //here is my query
   String queryStr = "select p from Person p where p.name LIKE :names.get(0) AND p.name LIKE :names.get(1) AND p.name LIKE :names.ger(2) AND......";

}

Please how can i write a such query using sql and jpql?


Solution

  • public void queryPersonsWhithNameLike(List names){ Iterate over the List and construct a query:

    String queryStr = "select p from Person p";
    int count=0;
    for(String str:names) {
       if(count==0) queryStr+="WHERE p.name LIKE :name"+count;
       else queryStr+=" AND p.name LIKE :name"+count;
       count++;
    }
    ... Initialize query
    for(String str:names) {
    ... Set all the :name+count as parameters
    }