【问题标题】:How to subclass Hibernate entity class effectively replacing the parent?如何子类化 Hibernate 实体类有效地替换父类?
【发布时间】:2015-11-29 08:55:07
【问题描述】:

鉴于以下情况:

  • 使用框架的项目
  • 框架定义了基本的实体类(用于日志记录、用户管理等)
  • 该项目具有特定于应用程序的实体类。

我想以一种不需要更改框架代码或特定于框架的数据库架构的方式对框架类进行子类化(除了可能由其他映射引入的任何约束)。

这是一个简化的框架类:

package com.example.parent;

@Entity
@Table("entities")
public class ExampleEntity {

    @Id
    @GeneratedValue
    protected Integer id;

    protected String name;

}

以及应用程序特定的扩展:

package com.example.child;

@Entity
public class ExampleEntity extends com.example.parent.ExampleEntity {

    @OneToMany
    @JoinColumn
    protected Set<OtherEntity> otherEntities;    

}

如您所见,这只是向特定于应用程序的实体类添加了一个附加映射。 这不适用于开箱即用的 Hibernate 4.3.11。它将尝试创建一个不需要的鉴别器列 (dtype),恕我直言,这里不需要。

我希望它尽可能透明(即不改变框架方面的任何东西)并且在应用程序中没有任何额外的手动映射/转换。实际上,我想诱使 Hibernate 只加载 com.example.child.ExampleEntity 的实例,而框架甚至都没有注意到。

TL;DR

如何欺骗 Hibernate 将 entities 表中的实体作为 com.example.child.ExampleEntity 的实例加载?

【问题讨论】:

    标签: hibernate-mapping jpa-2.1 hibernate-4.x


    【解决方案1】:

    您可以在父类上使用@Inheritance(strategy = InheritanceType.JOINED)。你可以找到一个例子here

    所以它可以与

    package com.example.parent;
    
    @Entity
    @Table("entities")
    @Inheritance(strategy = InheritanceType.JOINED)
    public class ExampleEntity {
    
        @Id
        @GeneratedValue
        protected Integer id;
    
        protected String name;
    
    }
    

    因此您可以将任何其他表加入到孩子或父母中

    This是关于继承映射的官方文档。

    【讨论】:

    • 我认为最初的问题是说如何在更改框架类的情况下使其工作,但我认为您建议通过添加@Inheritance 注释来修改框架类.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    相关资源
    最近更新 更多