Search code examples
javaspringhibernatejpacriteria

How to join one table with different tables with criteria API?


I have following classes:

class A {
    private B b;
    // getters/setters
}
class B {
   private C c;
   private D d;
   // getters/setters
}
class C {
   private boolean outdated;
   // getters/setters
}
class D {
   // not important fields
   // getters/setters
}

Class B is connected to A, C and D with relation 'one-to-one'.

I am trying to join following tables with criteria api.

I have following code:

Root<A> root = query.from(A.class);
root.join(A_.b)
    .join(B_.c)
    .join(B_.d);

But unfortunately this code will not compile, I will get error on line with ".join(B_.d)", because after joining B with C I cannot use fields of B for joining.

The reason why I want to make such joins is because I need to have condition that entity C is not outdated (so I will add 'on' condition for it).

Does anybody know how to solve this problem?


Solution

  • root.join(A_.b).join(B_.c) represents a C, so there is no way then to join to "B_.d". You would need to do

    Root<A> root = query.from(A.class);
    Join<A,B> bJoin = root.join(A_.b);
    bJoin.join(B_.c);
    bJoin.join(B_.d);