Setting a parameter as a list for an IN expression

前端 未结 9 2492
北荒
北荒 2020-11-30 07:14

Whenever I try to set a list as a parameter for use in an IN expression I get an Illegal argument exception. Various posts on the internet seem to indicate that this is poss

相关标签:
9条回答
  • 2020-11-30 08:16

    Oh, and if you can't use EclipseLink for some reason then here is a method you can use to add the needed bits to your query. Just insert the resulting string into your query where you would put "a.id IN (:ids)".

    
    
         /** 
         /* @param field The jpql notation for the field you want to evaluate
         /* @param collection The collection of objects you want to test against
         /* @return Jpql that can be concatenated into a query to test if a feild is in a 
         */
    collection of objects
        public String in(String field, List collection) {
            String queryString = new String();
            queryString = queryString.concat(" AND (");
            int size = collection.size();
            for(int i = 0; i > size; i++) {
                queryString = queryString.concat(" "+field+" = '"+collection.get(i)+"'");
                if(i > size-1) {
                    queryString = queryString.concat(" OR");
                }
            }
            queryString = queryString.concat(" )");
            return queryString;
        }
    
    0 讨论(0)
  • 2020-11-30 08:16

    IN :ids instead of IN (:ids) - will work.

    0 讨论(0)
  • 2020-11-30 08:17

    You can also try this syntax.

    static public String generateCollection(List list){
        if(list == null || list.isEmpty())
            return "()";
        String result = "( ";
        for(Iterator it = list.iterator();it.hasNext();){
            Object ob = it.next();
            result += ob.toString();
            if(it.hasNext())
                result += " , ";
        }
        result += " )";
        return result;
    }
    

    And put into query, "Select * from Class where field in " + Class.generateCollection(list);

    0 讨论(0)
提交回复
热议问题