Can I use SQL's IN(…) statement for a namedQuery?
-
11-10-2019 - |
문제
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.
해결책
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);
다른 팁
Did you try something like
SELECT p FROM Product p WHERE p.type= :type AND (p.available IN
('foo', 'bar') OR p.available = :available)
(if "available" is a string)
or
SELECT p FROM Product p WHERE p.type= :type AND (p.available IN
(1, 2, 3) OR p.available = :available)
(if available is a number)?
Expression 'IN' in JPQL is equal to writing multiple 'OR' statements, in your case an example of 'IN' would be:
... p.available IN ('US', 'GB') ...
Which I believe is equal to:
... p.available = 'US' OR p.available = 'GB' ...
Here's a link that explains it well: OpenJPA: IN Expression
EDIT P.S. Assuming p.available is String (character type)
EDIT2 The author has edited question so many times that I can't follow up him :) As for the actual question about passing array for IN-expression, here's a link of similar question on StackOverflow: JPQL IN clause - Arrays