【问题标题】:JPA deep inheritence annotation attributesJPA 深度继承注解属性
【发布时间】:2012-02-08 04:20:51
【问题描述】:

我有一个层次结构的 JPA 映射,它有几个类深。像这样的

@Entity
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
public abstract class BaseEntityClass implements Serializable {

    // lots of stuff common to all my entities.

} 

@Entity
@Inheritance(strategy= InheritanceType.TABLE_PER_CLASS)
public abstract class EntityTypeOne extends BaseEntityClass {
   // stuff common to EntityTypeOne
}

@Entity
@Inheritance(strategy= InheritanceType.TABLE_PER_CLASS)
public abstract class EntityTypeTwo extends BaseEntityClass {
   // stuff common to EntityTypeTwo
}

我知道您使用带有超类的@Inheritence 方法来定义映射策略。但这如何与深层层次结构一起工作?我希望将所有叶类映射到它们自己的表。我应该用 BaseEntityClass 做 SINGLE_TABLE 吗?

【问题讨论】:

    标签: java jakarta-ee inheritance jpa orm


    【解决方案1】:

    您的基类应标记为TABLE_PER_CLASS。以下是来自OpenJPA 的示例:

    @Entity
    @Table(name="MAG")
    @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
    public class Magazine {
        ...
    }
    
    @Entity
    @Table(name="TABLOID")
    public class Tabloid
        extends Magazine {
        ...
    }
    

    根据JPA JavaDocs,@Inheritance注解应该在类层次的根上指定:

    定义用于实体类的继承策略 等级制度。它在作为根的实体类上指定 实体类层次结构。

    如果这个注解可以放在一个子类上,规范没有规定,因此它的行为是未定义的。

    所以回答你在 cmets 中提出的问题,如果你有这个层次结构:

    SubSub -> Sub -> Base
    

    您只需将Base 注释为@Inheritance(strategy = TABLE_PER_CLASS)。

    【讨论】:

    • 那么是不是一个层次结构中的所有超类都必须具有相同的@Inheritence 注释?如果不是,那么有不同的注释意味着什么?
    猜你喜欢
    • 2016-01-21
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多