嵌套单表继承

时间:2011-12-12 13:21:46

标签: java hibernate single-table-inheritance

我遇到了对象模型和Hibernate的问题。我希望将整个模型存储为单个表。

我已经尝试过以下内容,但是当我要求Hibernate生成SQL创建文件时,它会创建3个表而不是1个。类层次结构可能看起来很奇怪,但它当然是脱离了上下文:)< / p>

尝试1:

@MappedSuperclass
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "CATEGORY", discriminatorType = DiscriminatorType.STRING, length  = 10)
@Table(name = "the_table")
public abstract class A {}

@MappedSuperclass
@DiscriminatorValue(value = "B")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING, length = 20)
public abstract class B extends A {}

@Entity
@DiscriminatorValue(value = "X")
public class X extends B {}

@Entity
@DiscriminatorValue(value = "Y")
public class Y extends B {}

@Entity
@DiscriminatorValue(value = "Z")
public class Z extends B {}

尝试2: 我们到达那里,而不是创建1个表,但没有生成鉴别器列。任何人都可以发现错误吗?

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "CATEGORY", discriminatorType = DiscriminatorType.STRING, length  = 10)
@DiscriminatorFormula(value = "CATEGORY || '_' || TYPE")
@Table(name = "the_table")
public abstract class A {}

@Entity
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING, length = 20)
public abstract class B extends A {}

@Entity
@DiscriminatorValue(value = "B_X")
public class X extends B {}

@Entity
@DiscriminatorValue(value = "B_Y")
public class Y extends B {}

@Entity
@DiscriminatorValue(value = "B_Z")
public class Z extends B {}

1 个答案:

答案 0 :(得分:2)

删除@MappedSuperclass并尝试。此外,您不能在单个层次结构中将@Inheritance标记两次 - 只使用一个。

如果要使用多列作为鉴别器,请使用@DiscriminatorFormula

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorForumula("CATEGORY || '_' || TYPE")
public abstract class A 

@Entity
@DiscriminatorValue(value = "B_X")
public class X extends A {}

@Entity
@DiscriminatorValue(value = "B_Y")
public class Y extends A {}

@Entity
@DiscriminatorValue(value = "B_Z")
public class Z extends A {}