CriteriaBuilder: join one-to-many with ON clause

痴心易碎 提交于 2019-12-10 10:26:08

问题


Suppose you the following OneToMany relationships: School->Student->ScientificWork. Now you want to select all Schools that have Student with name 'John' and his scientific job is called 'Black Holes'.

I do it like the following, but for some reason it retrurns me all possible schools.

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

After finding this answer I tried the following, but with the same result (it returns me all Schools instead of one):

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:


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 instead of joinSet and put **works**.get(ScientificWork_.name) instead of **nodes**.get(ScientificWork_.name)



来源:https://stackoverflow.com/questions/46793743/criteriabuilder-join-one-to-many-with-on-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!