gpt4 book ai didi

java - 处理 QueryDSL 中的可选参数

转载 作者:搜寻专家 更新时间:2023-10-30 19:48:40 24 4
gpt4 key购买 nike

我正在使用 QueryDSL 和 SpringData。我有表说 Employee 并且我创建了实体类说 EmployeeEntity我写了以下服务方法

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。如何使用 QueryDSL 使用 Spring Data 在 QueryDSL 中使用可选参数?

谢谢你:)

最佳答案

BooleanBuilder 可用作 boolean 表达式的动态构建器:

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

关于java - 处理 QueryDSL 中的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23750528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com