如何使用条件 API 加入一个 table 与不同的 table?

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

我关注类:

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 以关系 'one-to-one'.

连接到 A、C 和 D

我正在尝试根据条件 api 加入以下表格。

我有以下代码:

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

但不幸的是,这段代码无法编译,我会在“.join(B_.d)”线上出错,因为在将 B 与 C 连接后,我无法使用 B 的字段进行连接。

我之所以要进行这样的连接,是因为我需要有实体C没有过时的条件(所以我会为它添加'on'条件)。

有人知道如何解决这个问题吗?

root.join(A_.b).join(B_.c)代表一个C,所以没办法加入到"B_.d"。你需要做

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