gpt4 book ai didi

java - 嵌套单表继承

转载 作者:行者123 更新时间:2023-12-02 08:03:51 26 4
gpt4 key购买 nike

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

我已经尝试了以下操作,但是当我要求 Hibernate 生成 SQL 创建文件时,它创建了 3 个表,而不是仅 1 个。类层次结构可能看起来很奇怪,但它当然是断章取义的:)

尝试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 {}

最佳答案

删除@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 {}

关于java - 嵌套单表继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8474993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com