处理 QueryDSL 中的可选参数

2022-01-18 00:00:00 java spring-data querydsl

我正在使用带有 SpringData 的 QueryDSL.我有表说,Employee,我创建了实体类说,EmployeeEntity我写了以下 service 方法

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

如上所述,我注释了 NPException.如何使用 Spring Data 将 QueryDSL 用于 QueryDSL 中的可选参数?

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

谢谢你:)

推荐答案

BooleanBuilder 可以用作布尔表达式的动态构建器:

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

相关文章