hibernate-JPA,ManyToOne和TablePerClass或Joined:创建错误的外键

时间:2013-02-09 09:58:05

标签: hibernate generics jpa foreign-keys

我有这两个抽象类:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="compound")
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<>();
}

@Entity 
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name="containable")
public abstract class Containable<T extends Compound> {     

    @ManyToOne(optional=true, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private T compound;
}

在我的测试中,我有两个实现,TestCompound和TestContainable作为一对,RegistrationCompound和Batch作为另一对。 (例如public class TesCompound extends Compound<TestContainable>public class RegistrationCompound extends Compound<Batch>)。

两个层次结构的TABLE_PER_CLASS

我面临的问题是hibernate从test_containable表创建一个外键约束到registration_compound而不是test_compound。它似乎没有得到通用关系。

加入两个层次结构(忽略我的情况下的缺点)

这里要求Compound和Containable是具体类(不是抽象的) 还有类似的问题。 hibernate从containsable创建外键约束 - &gt;复合(预期),但也包含来自可包含的外键约束 - &gt; registration_compound(意外)。我不知道为什么要创建它?更令人困惑的是,没有这种限制可以包含 - &gt; test_compound

总而言之,令人困惑。将尝试single_table但这是最不希望的选项...

1 个答案:

答案 0 :(得分:1)

这是由错误的映射引起的。

@ManyToOne(optional=true, fetch = FetchType.EAGER, cascade = CascadeType.ALL,
    targetEntity = Compound.class)
private T compound;

targetEntity缺失,出于某种原因,hibernate只假设其中一个实现是目标。有点烦人......