假设您有以下 OneToMany 关系:School->Student->ScientificWork
。现在您想要选择所有学生名为“John”且他的科学工作称为“黑洞”的学校。
我按照以下方式进行操作,但由于某种原因它返回了我所有可能的学校。
public static Specification<School> spec() {
return (root, query, cb) -> {
final SetJoin<School, Student> studs = root.joinSet("students", JoinType.LEFT);
final SetJoin<Student, ScientificWork> works = root.joinSet("works", JoinType.LEFT);
return cb.and(
cb.equal(studs.get(Student_.name), 'John'),
cb.equal(nodes.get(ScientificWork_.name), 'Black Holes')
);
};
}
Update
找到后这个答案 https://stackoverflow.com/questions/15990141/how-to-make-a-criteriabuilder-join-with-a-custom-on-condition/37993919#37993919我尝试了以下操作,但结果相同(它返回所有学校而不是一所):
public static Specification<School> spec() {
return (root, query, cb) -> {
final SetJoin<School, Student> studs = root.joinSet("students", JoinType.LEFT);
studs.on(cb.equal(studs.get(Student_.name), 'John'));
final SetJoin<Student, ScientificWork> works = root.joinSet("works", JoinType.LEFT);
return cb.equal(nodes.get(ScientificWork_.name), 'Black Holes');
};
}