CriteriaBuilder:使用 ON 子句加入一对多
CriteriaBuilder: join one-to-many with ON clause
假设您有以下 OneToMany 关系:School->Student->ScientificWork
。现在您想要 select 所有拥有姓名为 'John' 且他的科学工作名为 'Black Holes' 的学校。
我是这样做的,但出于某种原因,它会返回所有可能的学校。
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')
);
};
}
更新
找到 this answer 后,我尝试了以下方法,但结果相同(它 returns 我所有的学校而不是一个):
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');
};
}
public static Specification<School> spec() {
return (root, query, cb) -> {
final Join<School, Student> studs = root.join("students", JoinType.LEFT);
studs.on(cb.equal(studs.get(Student_.name), "John"));
final Join<Student, ScientificWork> works = studs.join("works", JoinType.LEFT);
return cb.equal(works.get(ScientificWork_.name), "Black Holes");
};
}
我使用 join 而不是 joinSet 并使用 **works**.get(ScientificWork_.name)
而不是 **nodes**.get(ScientificWork_.name)
假设您有以下 OneToMany 关系:School->Student->ScientificWork
。现在您想要 select 所有拥有姓名为 'John' 且他的科学工作名为 'Black Holes' 的学校。
我是这样做的,但出于某种原因,它会返回所有可能的学校。
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')
);
};
}
更新
找到 this answer 后,我尝试了以下方法,但结果相同(它 returns 我所有的学校而不是一个):
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');
};
}
public static Specification<School> spec() {
return (root, query, cb) -> {
final Join<School, Student> studs = root.join("students", JoinType.LEFT);
studs.on(cb.equal(studs.get(Student_.name), "John"));
final Join<Student, ScientificWork> works = studs.join("works", JoinType.LEFT);
return cb.equal(works.get(ScientificWork_.name), "Black Holes");
};
}
我使用 join 而不是 joinSet 并使用 **works**.get(ScientificWork_.name)
而不是 **nodes**.get(ScientificWork_.name)