Search code examples
javacriteria

If statement inside criteriaBuiilder


I have something like that:

    criteria.select(something.get("somethingId"))
            .where(builder.and(
                    builder.equal(something.get("firstColumn"), firstValue),
                    builder.equal(something.get("thirdColumn", thirdValue), 
            ));

and want to do add into where something like this:

secondValue != 0 ? builder.equal(something.get("secondColumn"), secondValue) : DONOTHING;

So shortly: if the value of secondValue is different than "0" i don't want to set builder.equal(secondColumn). And I want to use that if inside builder if it is possible because this builder will be really long so I want to avoid code duplication.

The problem is that this if condition cannot be empty after semicolon and from the other hand I cannot use normal if(secondValue != 0) inside this builder expression.

Can you help me with that?


Solution

  • A pattern I find usefull for building JPA criterias is to use a List to add predicates into. That allows you to add some of them conditionally a lot more easily:

    List<Predicate> predicateList = new ArrayList<>();
    
    predicateList.add(builder.equal(something.get("firstColumn"), firstValue));
    predicateList.add(builder.equal(something.get("thirdColumn", thirdValue));
    if(secondValue != 0) {
        predicateList.add(builder.equal(something.get("secondColumn", secondValue));
    }
    
    criteria.select(something.get("somethingId"))
            .where(predicateList.toArray(new Predicate[predicateList.size()]);
    

    Note that if you add multiple predicates as an Array to the where method of javax.persistence.criteria.CriteriaQuery they will automatically be added as a conjunction, so wrapping all of them in a builder.and is not necessary.