let me get straight to the point. I am using Spring Data JPA with QueryDSL in a project and I cannot figure out this myself.
I have the QueryDSL predicates in static methods that can take arguments and if the argument is not correct it should return "empty predicate" :
public static BooleanExpression byWhateverId(Long whateverId) {
if(whateverId == null) return [insert magic here];
// if parameter is OK return usual predicate
return QClass.property.whateverId.eq(whateverId);
}
Now I want to be able to chain these predicates using AND/OR oprators :
someRepository.findAll(byWhateverId(someParam).and(bySomethingElseId(1));
The problem here is that at this point I don't know whether 'someParam' is null or not (of course I can check but that's a lot of IFs). I also know I can use BooleanBuilder class but that seems also like a lot of code that should not be needed.
Does anybody knows what could be inserted instead of "[insert magic here]" ??? Or maybe I am missing something somewhere...
Thanks!
You can return null for non matching predicates in byWhateverId
and bySomethingElseId
and combine the predicate via ExpressionUtils.allOf()
In your case
Predicate where = ExpressionUtils.allOf(byWhateverId(someParam), bySomethingElseId(1));
someRepository.findAll(where);
4 years old question, but anyway...
You can return sql predicate which is always true, like true=true:
public static BooleanExpression alwaysTrue() {
return Expressions.TRUE.isTrue;
}
If you have a bunch of these the generated sql won't be super nice, so you might want to limit such usages to a minimum.
Sorry, I completely forgot about this. The right solution (from my point of view) is to use BooleanBuilder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With