I’ve got query that looks something like this:
SomeDomain.executeQuery("""
from
SomeDomain x
where
x.linkToSomeA = coalesce(:a, x.linkToSomeA) and
x.linkToSomeB = coalesce(:b, x.linkToSomeB) and
...
""",
[a: someA, b: someB, ...]
)
The intended behaviour is as follows: once null is supplied for a criterion parameter, this criterion should be ignored. If anything other than null is supplied, the criterion is used.
Everything would work fine, except that Hibernate doesn’t allow supplying null where domain class instances are expected. So in the end this is not a valid query (in fact NullPointerException will be thrown if any nulls are supplied).
I haven’t found any way to rewrite this without using a ton of if-else. Does anybody have any idea how to make this about equally brief and valid at the same time?
NOTE: The real query is more complicated than that so please, do not suggest rewriting this using anything else than executeQuery.
This is generally for this kind of problem that the Criteria api is used: it allows building a query dynamically:
This answer doesn’t follow your request of not using anything else than
executeQuery, but you might also ask how to build a house using nothing else than a screwdriver, and the best answer would still be “buy some other tools”).