Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data + QueryDSL empty predicate + Predicate chaining

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!

like image 666
user1622058 Avatar asked Nov 23 '14 14:11

user1622058


3 Answers

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);
like image 196
Timo Westkämper Avatar answered Nov 12 '22 18:11

Timo Westkämper


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.

like image 28
Madis Avatar answered Nov 12 '22 20:11

Madis


Sorry, I completely forgot about this. The right solution (from my point of view) is to use BooleanBuilder.

like image 5
user1622058 Avatar answered Nov 12 '22 20:11

user1622058