【问题标题】:Is it Possible to force a Discriminator While using the Joined Inheritance Strategy使用联合继承策略时是否可以强制使用鉴别器
【发布时间】:2017-10-16 22:21:47
【问题描述】:

为了我的数据库管理员,我不得不使用 Joined Inheritance Strategy,这会更容易使用 Single.Table 但是嗯,所以让我们说一个实体:

@Entity
    @Inheritance(strategy = InheritanceType.JOINED)
    public abstract class Post{
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            protected Long id;
            protected String title;
            protected String d_type;// I want this to to be the discriminator.
}

还有孩子:

    @Entity
    public abstract class Book{
            protected String title;
}

为了一个好的答案,示例很简单,但实际上我正在处理 5 个“孩子”,每个“孩子”都有其特定的属性和方法,除了一个让我们称之为 CommonPost已经提供了,这就是为什么我要添加一个具有枚举类型的鉴别器,如下所示 {xPost,yPost,..,CommonPost}。首先它是否可能甚至实用?如果不是,还有什么更好的选择实用。

【问题讨论】:

    标签: hibernate jpa inheritance jakarta-ee


    【解决方案1】:

    这是可能的,但如果支持,您可以咨询您的 JPA 供应商。我相信 Hibernate 支持这一点。他们称之为混合继承策略:

    这是一个示例:

    @Inheritance(strategy = InheritanceType.JOINED)
    @DiscriminatorColumn(name="POST_TYPE")
    public abstract class Post{
    

    从技术上讲,这是一种 JOINED 策略,但没有什么能阻止您添加鉴别器列(通常用于 SINGLE-TABLE 策略)。

    还有另一个建议:如果你说实体CommonPost 没有任何特定的属性或方法,那么为什么不让它成为你继承层次结构中最顶层的类呢?然后你现在可以消除抽象类Post

    你可以这样做:

    @Inheritance(strategy = InheritanceType.JOINED)
    @DiscriminatorColumn(name="POST_TYPE")
    @DiscriminatorValue("C")
    public class CommonPost {
    ...
    @DiscriminatorValue("X")
    public class XPost extends CommonPost {
    ...
    @DiscriminatorValue("Y")
    public class YPost extends CommonPost {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-08
      • 2019-02-17
      • 2015-02-21
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      相关资源
      最近更新 更多