java Hibernate 鉴别器列,每个子类都有表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6202816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:48:54  来源:igfitidea点击:

Hibernate discriminator column with table per subclass

javahibernate

提问by Ransom Briggs

Right now I am using a table per subclass approach to model my data. A simplification of my hierarchy is:

现在我正在使用每个子类的表来为我的数据建模。我的层次结构的简化是:

abstract class Abstract {
    /* common data stored in abstract */
}

class ConcreteTypeA1 extends Abstract {
    /* extra data stored in concrete_type_a_1 */
}

class ConcreteTypeA2 extends Abstract {
    /* extra data stored in concrete_type_a_2 */
}

class ConcreteTypeB extends Abstract {
    /* extra data stored in concrete_type_b */
}

So it does three outer joins where I grab instances of type Abstract (in reality it is twelve). What I realized yesterday is that ConcreteTypeA1 and ConcreteTypeA2 really have the same extra data, they just behave differently, so what I would like to do is reduce the number of joins by stuffing these two classes into one table and using a discriminator column. How / can I accomplish this?

所以它执行三个外部连接,我在其中获取 Abstract 类型的实例(实际上是十二个)。昨天我意识到 ConcreteTypeA1 和 ConcreteTypeA2 确实具有相同的额外数据,只是它们的行为不同,所以我想做的是通过将这两个类填充到一个表中并使用鉴别器列来减少连接的数量。我如何/我能做到这一点?

class Abstract {
    /* common data stored in abstract */
}

abstract class ConcreteTypeA extends Abstract {
    /* extra data stored in abstract_type_a */
}

class ConcreteTypeA1 extends ConcreteTypeA {
    /* just behavior, no extra data, uses data in abstract_type_a */
}

class ConcreteTypeA2 extends ConcreteTypeA {
    /* just behavior, no extra data, uses data in abstract_type_a */
}

class ConcreteTypeB extends Abstract {
    /* extra data stored in concrete_type_b */
}

采纳答案by Ransom Briggs

Used answer from this question as per Vincents' advice.

根据文森特的建议使用了这个问题的答案。

How to mix inheritance strategies with JPA annotations and Hibernate?

如何将继承策略与 JPA 注释和 Hibernate 混合使用?

回答by Manoj

use this on Parent class

在父类上使用它

@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="type",
    discriminatorType=DiscriminatorType.STRING)

and on concrete classes use

并在具体类上使用

@DiscriminatorValue("TypeA")