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

问题描述 投票:0回答:1

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

更新

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

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');
    };
}
hibernate spring-data-jpa spring-data criteria-api
1个回答
3
投票
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)

© www.soinside.com 2019 - 2024. All rights reserved.