Search code examples
javaspringjpa-criteria

How to avoid NPE when no values is specified for Spring JPA criteria


I have a Spring JPA search criteria like below. Where area is an Integer.

cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())

The question is, when the user does not specify an upper bound or lower bound in the search, the value is null and this results in NPE. One thing comes to my mind is to make an if check for null values and set the value to Integer.MAX_VAL if it is null as a work around.This way I can avoid NPE, but it is also going to create a lot of if else checks. So I want to know if there is a better way.


Solution

  • Two cleaner solutions come to my mind:

    • using Optionals e.g. `Optional.ofNullable(searchConstraint.getAreaMax()).orElse(Integer.MAX_VALUE)
    • areaMin and areaMax should have sensible default values which are overwritten only if user provided some data ; the data itself should be validated