小编典典

CriteriaBuilder:使用ON子句一对多连接

hibernate

假设您具有以下一对多关系:School->Student->ScientificWork。现在,您要选择所有学生名为“ 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')
        );
    };
}

更新资料

找到此答案后,我尝试了以下操作,但结果相同(它使我返回所有学校而不是所有学校):

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

阅读 612

收藏
2020-06-20

共1个答案

小编典典

public static Specification spec() {
return (root, query, cb) -> {
final Join studs = root.join(“students”, JoinType.LEFT);
studs.on(cb.equal(studs.get(Student_.name), “John”));
final Join works = studs.join(“works”, JoinType.LEFT);
return cb.equal(works.get(ScientificWork_.name), “Black Holes”);
};

}

我用 join 代替 joinSet, 然后用put**works**.get(ScientificWork_.name)代替**nodes**.get(ScientificWork_.name)

2020-06-20