Search code examples
javaspring-data-jpaquerydsl

Equating value after testing for nullability in querydsl


I am using querydsl with spring-data-jpa. When a value is retrieved from my rest controller, it can or cannot be null. Lets assume that I have following class:

@Entity
class Person {

    @Id private String name;

    private int age;
}

I have created a BooleanExpression as below:

public static final BooleanExpression hasName(String name) {
    return QPerson.name.isNotNull().and(QPerson.name.eq(name));
}

When this is executed by PersonRepository#findAll(...), the following exception is thrown:

java.lang.IllegalArgumentException: eq(null) is not allowed. Use isNull() instead
    at com.querydsl.core.types.dsl.SimpleExpression.eq(SimpleExpression.java:127) ~[querydsl-core-4.1.4.jar:na]

Can you please help me in fixing this exception?


Solution

  • The Exception seems to say that the argument to hasName is null. Try:

    return name==null ? QPerson.name.isNull() : QPerson.name.eq(name);