简体   繁体   中英

Spring(Specification) - How to create Criteria Builder with manyToMany relationship and collection

I have a problem to found a solution for spring specifications with list of objects and @ManyToMany relationship. I have employee entity class which have list of skills:

@Entity
public class EmployeeEntity {
    @ManyToMany
    @JoinTable(name = "employee_skill",
        joinColumns = {@JoinColumn(name = "employee_id")},
        inverseJoinColumns = {@JoinColumn(name = "skill_id")})
    private List<SkillEntity> skills;
}

public class SkillEntity {
    @Column(name  = "skill_name")
    private String skillName;
}

I want to find employees which have skills which are stored in my custom list of skills:

public static Specification<EmployeeEntity> employeeHasSkills(List<String> skills) {
    return (root, query, cb) ->{
        return root.get("skills").get("skillName").in(skills);
    };
}

List of skills has skillNames as String. So I try to map skills for skillName. Ofc this is not working. Any idea? I'm looking for solution without JPA metamodel.

root.get("skills") returns List<Skill> . It does not have skillName .

You should try something like this

public static Specification<EmployeeEntity> employeeHasSkills(List<String> skills) {
    return (root, query, cb) ->{
        Join<EmployeeEntity, SkillEntity> skill = root.join("skills", JoinType.LEFT);
        return skill.get("skillName").in(skills);
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM