如何用QueryDSL筛选所有Task优先级均高于指定值的Employee
解决QueryDSL筛选所有关联Task优先级均高于指定值的Employee问题
问题场景
你已经通过QueryDSL的any()方法实现了查询至少有一个Task优先级高于指定值的Employee,但需要实现筛选所有关联Task优先级均高于指定值的Employee。
解决方案
QueryDSL中没有直接的“遍历所有元素”的API,但可以通过反向逻辑实现需求:要所有Task的优先级都大于指定值,等价于不存在任何一个Task的优先级小于等于指定值。可以使用none()方法来表达这个逻辑。
修改你的代码,添加allHigher的条件处理:
@Getter @Setter @ToString @ApiModelProperty("contains ignore case") private String name; @ApiModelProperty("equals") private String department; @ApiModelProperty("in equals") private List<String> position; @ApiModelProperty("greater or equals") private Integer salaryFrom; @ApiModelProperty("lower or equals") private Integer salaryTo; @ApiModelProperty("contains ignore case") private String email; @ApiModelProperty("at least one with priority higher") private Integer oneHigher; @ApiModelProperty("all priorities higher") private Integer allHigher; // 构建查询条件 BooleanBuilder conditions = new BooleanBuilder(); ofNullable(salaryFrom).map(employee.salary::goe).ifPresent(conditions::and); ofNullable(salaryTo).map(employee.salary::loe).ifPresent(conditions::and); ofNullable(email).map(employee.email::containsIgnoreCase).ifPresent(conditions::and); ofNullable(oneHigher).map(employee.tasks.any().priority::goe).ifPresent(conditions::and); // 添加所有Task优先级均高于指定值的条件 ofNullable(allHigher) .map(val -> employee.tasks.none().priority.loe(val)) // 逻辑:不存在优先级<=指定值的Task .ifPresent(conditions::and); return conditions;
逻辑说明
employee.tasks.none().priority.loe(val)的含义是:当前Employee的所有Task中,没有任何一个的优先级小于等于val,反向推导就是所有Task的优先级都大于val,完全匹配你的需求。- 这种方式无需编写复杂子查询,符合QueryDSL的API设计思路,代码更简洁易读。
内容的提问来源于stack exchange,提问作者Kacper Szczęsny
相关产品推荐
相关产品推荐

