Can I use SQL's IN(...) statement for a namedQuery?

kamaci picture kamaci · Dec 20, 2010 · Viewed 28.4k times · Source

How can I use IN at my namedQuery?

@NamedQueries(  
 {   
 @NamedQuery(name = "GetAvailableProducts", query = new StringBuilder("").append("SELECT   p   FROM Product p WHERE p.type= :type AND (p.available IN ('I want to define changeable size of an array or sometinhg like that') OR p.available = :available)")),  
 }

I mean that I can set 'type' parameter (I defined it as a variable----> :type) and I want to define variables inside of IN statement to. However the number of parameters are not constant. I want to define an array or something like that :array[] and I want to set it when I call that namedQuery.

Answer

Tadeusz Kopec picture Tadeusz Kopec · Dec 20, 2010

NamedQuery

@NamedQueries(  
{   
 @NamedQuery(name = "GetAvailableProducts", query = "FROM Product p WHERE p.type= :type AND (p.available IN (:availableCollection) OR p.available = :available)",  
}

Set parameters

Hibernate:

query.setParameterList('availableCollection', yourCollection);

JPA:

query.setParameter('availableCollection', yourCollection);