2013-02-08 60 views
2

我有这2类:Java泛型“反向关系”(和JPA)

@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; 
} 

我想在一个类型安全的方式实现的是,化合物的具体实施只接受特定的实现可容纳的,反之亦然。

我该如何做到这一点?

编辑:

我已经从asenovm的解决方案,只是想仔细检查它实际上是正确的。

我的后续问题是,如果我有class Compound<T extends Containable>class Containable<T extends Compound> Containable和Compound是原始类型还是我得到错误?因为在class Compound<T extends Containable> T实际上是一个Containable而不是其他任何东西。

回答

2

也许这样的事情?

@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; 
} 
+0

这也是我的第一个想法,但它不适用于每个类的JPA(Hibernate)和Table。 - >在为化合物A插入一个可容纳对象时出现外键约束违规,它说:“表中没有记录,其ID为xyz的化合物B”。 – 2013-02-09 07:57:20

+0

并且用'ChemicalCompound 'Compound的一种方法,'compound.getCompositions()'现在似乎返回List而不是列表。 (不兼容的类型编译错误)。对我没有意义... – 2013-02-09 08:32:51