5

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');
    };
}
snieguu
  • 2,073
  • 2
  • 20
  • 39
VB_
  • 45,112
  • 42
  • 145
  • 293
  • Is this possible? Do someone need any additional details? – VB_ Oct 18 '17 at 11:34
  • 2
    have you mistakenly used nodes instead of works? – Mudassar Oct 18 '17 at 11:40
  • This line ` final SetJoin works = root.joinSet("works", JoinType.LEFT);` should have been ` final SetJoin works = **studs**.joinSet("works", JoinType.LEFT);` or it is a typo ? – hzitoun Oct 19 '17 at 07:37

1 Answers1

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

}

I used join instead of joinSet and put **works**.get(ScientificWork_.name) instead of **nodes**.get(ScientificWork_.name)

hzitoun
  • 5,492
  • 1
  • 36
  • 43