Handle optional parameters in QueryDSL

Prashant Shilimkar picture Prashant Shilimkar · May 20, 2014 · Viewed 20k times · Source

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 :)

Answer

Timo Westkämper picture Timo Westkämper · May 27, 2014

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);
}