Spring boot 弹簧靴;JPA:CriterialBuilder检查字符串是否包含表达式<;字符串>;

Spring boot 弹簧靴;JPA:CriterialBuilder检查字符串是否包含表达式<;字符串>;,spring-boot,spring-data-jpa,jpql,Spring Boot,Spring Data Jpa,Jpql,1.)我想使用表达式和字符串模式获取表达式。 如果表达式包含在字符串模式中,则应该为true,而不是相反 字符串模式可以看起来像“MFD”或“MF”或三个字母M、F、D的任何其他组合。表达式可以是M、F或D 到目前为止,我有以下代码,但我认为有一个更好的解决方案 public class AthleteSpecification implements Specification<Athlete> { private String gender; public A

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

    } 

}

公共类AthleteSpecification实现了该规范{
私人字符串性别;
公共AthleteSpecification(字符串性别){
超级();
这个。性别=性别;
}
@凌驾
公共谓词toPredicate(根根、CriteriaQuery查询、CriteriaBuilder cb){
谓词p=cb.析取();
if(this.gender==null){
返回cb.conjunction();
}否则{
表达为男性或女性或女性;
if(this.gender!=null){
//这是一个可行的解决方案,但并不好
表达式isMale=cb.equal(root.get(“性别”),gender.contains(“M”)?“M”:“”;
表达式isMaleOrFemale=cb.or(isMale,
cb.equal(root.get(“gender”)、gender.contains(“F”)?“F”:“);
IsmaleOrFemaleOrderivers=cb.或(IsmaleOrFemaleOrderivers,
cb.equal(root.get(“gender”)、gender.contains(“D”)?“D”:“);
//这不是一个解决方案,因为我认为它只检查字符串是否在表达式中,而不是相反
//表达式测试=cb.locate(root.get(“性别”),性别);
//isMaleOrFemaleorDivers=cb.大于(测试,0);
}否则{
isMaleOrFemaleorDivers=cb.conjunction();
}
p、 getExpressions().add(cb.and(isNameMatching,IsMaleOrFemaleOrderivers));
返回p;
}
} 
}

在堆栈溢出时,我们希望每个问题有一个问题。请编辑此问题以仅包含一个问题,并为另一个问题创建单独的问题。我已编辑了我的问题检查此问题的答案是否有用--