I am trying to write a partially dynamic HQL query without resorting to the Critics API for various reasons. I would like to know if there is an easy way to shorten a constraint using HQL expressions. For example, here is the original query that works fine:
SELECT customer FROM Customer as customer INNER JOIN customer.profile as profile WHERE profile.status IN :statusCodes AND profile.orgId IN :orgIds
StatusCodes is a list of strings, and orgIds is a list of integers. However, one of them is optional and should not limit the transfer of null instead of the collection. I tried to do it like this:
SELECT customer FROM Customer as customer INNER JOIN customer.profile as profile WHERE (:statusCodes IS NULL OR profile.status IN :statusCodes) AND (:orgIds IS NULL OR profile.orgId IN :orgIds)
Unfortunately, this did not work, but is there any other approach that can work, either using different expressions or passing default values?
EDIT: just to be clear, I'm looking for a way to use NamedQuery, rather than dynamically building the query in any way.
SOLUTION: I used additional query parameters to execute it. I created two helper methods:
private void setRequiredParameter(TypedQuery<?> query, String name, Object value) { query.setParameter(name, value); } private void setOptionalParameter(TypedQuery<?> query, String name, Object value) { query.setParameter(name, value); query.setParameter(name + "Optional", value == null ? 1 : 0); }
And the request looks like this:
SELECT customer FROM Customer as customer INNER JOIN customer.profile as profile WHERE (:statusCodesOptional = 1 OR profile.status IN :statusCodes) AND (:orgIdsOptional = 1 OR profile.orgId IN :orgIds)