Spring Data + QueryDSL empty predicate + predicate chain

Let me get straight to the point. I am using Data JPA with QueryDSL in a project and I cannot figure it out myself.

I have QueryDSL predicates in static methods that can take arguments, and if the argument is invalid, it should return an "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 link these predicates with AND / OR oprators:

someRepository.findAll(byWhateverId(someParam).and(bySomethingElseId(1));

      

The problem is that at the moment I don't know if "someParam" is null or not (of course I can check, but there are a lot of IFs). I also know I can use the BooleanBuilder class, but that seems like a lot of code that is unnecessary.

Does anyone know what can be inserted instead of "[insert magic here]" ??? Or maybe I am missing something ...

Thank!

+3


source to share


1 answer


You can return null for mismatched predicates in byWhateverId

and bySomethingElseId

and concatenate the predicate withExpressionUtils.allOf()

In your case



Predicate where = ExpressionUtils.allOf(byWhateverId(someParam), bySomethingElseId(1));
someRepository.findAll(where);

      

+8


source







All Articles