spring-boot - Spring Boot 和 JPA:CriterialBuilder 检查字符串是否包含表达式
问题描述
1.) 我想使用表达式和字符串模式获得表达式。如果表达式包含在字符串模式中而不是其他方式,则它应该成为 true。
字符串模式可能看起来像“MFD”或“MF”或三个字母 M、F、D 的任何其他组合。表达式为 M、F 或 D。
到目前为止,我有以下代码,但我认为有更好的解决方案。
public class AthleteSpecification implements Specification<Athlete> {
private String gender;
public AthleteSpecification(String gender) {
super();
this.gender = gender;
}
@Override
public Predicate toPredicate(Root<Athlete> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate p = cb.disjunction();
if (this.gender == null) {
return cb.conjunction();
} else {
Expression<Boolean> isMaleOrFemaleorDivers;
if (this.gender != null) {
// This is a working solution but not nice
Expression<Boolean> isMale = cb.equal(root.get("gender"), gender.contains("M") ? "M" : "");
Expression<Boolean> isMaleOrFemale = cb.or(isMale,
cb.equal(root.get("gender"), gender.contains("F") ? "F" : ""));
isMaleOrFemaleorDivers = cb.or(isMaleOrFemale,
cb.equal(root.get("gender"), gender.contains("D") ? "D" : ""));
// This is not a solution because i think it only checks if the String is in the Expression<String> not the other way
// Expression<Integer> test = cb.locate(root.get("gender"), gender);
// isMaleOrFemaleorDivers = cb.greaterThan(test, 0);
} else {
isMaleOrFemaleorDivers = cb.conjunction();
}
p.getExpressions().add(cb.and(isNameMatching, isMaleOrFemaleorDivers));
return p;
}
}
}
解决方案
推荐阅读
- windows - 为什么 `agile_ref` 会因某些对象(例如 `CoreWindow`)而失败?
- typescript - 您如何将“keyof T”表示为字符串的子集?
- docker - Google Cloud Composer - 部署 Docker 映像
- php - 队列::推送错误 - laravel
- ios - Swift:拉动刷新太敏感了
- wolfram-mathematica - 忽略 Mathematica 中具有多个变量的方程的一部分
- node.js - 如何保留简单的数据供所有用户查看
- angular - 类型“Observable<{}[]>”不可分配给类型“BrandElement[]”。'Observable<{}[]>' 类型中缺少属性 'includes'
- javascript - Javascript onclick不起作用,连续点击多个图像
- android - React Native Fetch API 返回旧数据