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

2024-03-01

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

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

}

I used join代替joinSet并把**works**.get(ScientificWork_.name)代替**nodes**.get(ScientificWork_.name)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CriteriaBuilder:使用 ON 子句连接一对多 的相关文章

随机推荐