CriteriaBuilder:使用ON子句加入一对多

时间:2017-10-17 15:24:53

标签: hibernate spring-data spring-data-jpa hibernate-criteria criteria-api

假设您有以下OneToMany关系: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')
        );
    };
}

更新

找到this answer后,我尝试了以下内容,但结果相同(它返回了所有学校而不是一个):

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

1 个答案:

答案 0 :(得分:2)

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

}

我使用加入而不是 joinSet 并将**works**.get(ScientificWork_.name)代替**nodes**.get(ScientificWork_.name)