'Can I check in a criteriabuilder chain if value is empty?

I have a criteria builder chain of gets, but they can be null which means they will fail.

example:

predicates.add(cb.equal(house.get("adressInfo").get("streetname"),value)

If for example house.get(adressInfo) is empty I still want it returned with an empty list or just null values for everything is fine. I only need to filter out for as an example houses with street name "A" but must also include all houses that have an empty adressInfo.

Now I get a null.streetname invalid access error because a house has an adressInfo of null



Solution 1:[1]

You could maybe work around this by introducing helper methods like this:

private String getStreet(House house) {
    AddressInfo addressInfo = (AdressInfo) house.get("adressInfo");
    return addressInfo == null ? null : addressInfo.get("streetname");
}

And then you can do:

predicates.add(cb.equal(getStreet(house), value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1