我有这两个类(class):
@Entity
public abstract class Compound {
@OneToMany(fetch = FetchType.EAGER, mappedBy="compound",
targetEntity=Containable.class, cascade = CascadeType.ALL)
private Set<Containable> containables = new HashSet<>();
}
@Entity
public abstract class Containable {
@ManyToOne(optional=true, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Compound compound;
}
我想要以类型安全的方式实现的是,Compound 的特定实现仅接受 Containable 的特定实现,反之亦然。
我怎样才能实现这个目标?
编辑:
我已经从asenovm 得到了解决方案,只是想仔细检查它是否确实是正确的。
我的后续问题是,如果我有 class Compound<T extends Containable>
和class Containable<T extends Compound>
Containable 和Compound 是原始类型还是我弄错了?因为在 class Compound<T extends Containable>
T 实际上是一个 Containable,而不是其他任何东西。
最佳答案
也许是这样的?
@Entity
public abstract class Compound<T extends Containable> {
@OneToMany(fetch = FetchType.EAGER, mappedBy="compound",
targetEntity=Containable.class, cascade = CascadeType.ALL)
private Set<T> containables = new HashSet<T>();
}
@Entity
public abstract class Containable<T extends Compound> {
@ManyToOne(optional=true, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private T compound;
}
关于Java 泛型 "reverse relationship"(和 JPA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14771979/