Search code examples
javaspring-dataquerydsl

Handle optional parameters in QueryDSL


I am using QueryDSL with SpringData. I have Table say, Employee and I have created entity class say, EmployeeEntity I have written following service method

public EmployeeEntity getEmployees(String firstName, String lastName)
{
    QEmployeeEntity employee = QEmployeeEntity.employeeEntity;
    BooleanExpression query = null;
    if(firstName != null)
    {
        query = employee.firstName.eq(firstName);
    }
    if(lastName != null)
    {
        query = query.and(employee.lastName.eq(lastName)); // NPException if firstName is null as query will be NULL
    }
    return empployeeDAO.findAll(query);
}

As in above I commented the NPException. How to use QueryDSL for optional Parameters in QueryDSL using Spring Data?

Thank you :)


Solution

  • BooleanBuilder can be used as a dynamic builder for boolean expressions:

    public EmployeeEntity getEmployees(String firstName, String lastName) {
        QEmployeeEntity employee = QEmployeeEntity.employeeEntity;
        BooleanBuilder where = new BooleanBuilder();
        if (firstName != null) {
            where.and(employee.firstName.eq(firstName));
        }
        if (lastName != null) {
            where.and(employee.lastName.eq(lastName));
        }
        return empployeeDAO.findAll(where);
    }