1.) Я хочу получить выражение, используя выражение и шаблон строки. Оно должно стать истинным, если выражение включено в шаблон строки, а не наоборот.
Шаблон строки может выглядеть как «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;
}
}
}