Saturday, December 15, 2012

JPQL IN clause

There are two ways to write IN clause in JPQL

1. conventional way
    Pass in a comma separated String into the query 
 
    StringBuffer jpql = new StringBuffer();
    jpql.append("SELECT a FROM TABLE_A a");
    jpql.append("WHERE a.id IN (:idList)");
    Query query = entityManager.createQuery(jpql.toString());
    query.setParameter("idList", idList);
        in this case, idList is a comma separated string, eg. "1, 2, 3, 4"


2. passed in a java.util.List object  
StringBuffer jpql = new StringBuffer();
jpql.append("SELECT a FROM TABLE_A a");
jpql.append("WHERE a.id IN :idList");
Query query = entityManager.createQuery(jpql.toString());
query.setParameter("idList", idList);
    in this case, idList is a java.util.List object. eg. [1, 2, 3, 4]
    note: when passing a java.util.List to a JPQL IN clause, (...) is not required

LinkWithin

Related Posts Plugin for WordPress, Blogger...