简体   繁体   中英

JPA deep inheritence annotation attributes

I have a hierarchical JPA mapping that is several Classes deep. Something like this

@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
}

I know you use the @Inheritence method with the superclass to define the mapping strategy. But how does this work with deep hierarchies? I want all the leaf classes to be mapped to their own tables. Should I do SINGLE_TABLE with BaseEntityClass?

Your base class should be marked TABLE_PER_CLASS . Here's an example from OpenJPA :

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

@Entity
@Table(name="TABLOID")
public class Tabloid
    extends Magazine {
    ...
}

According to the JPA JavaDocs , the @Inheritance annotation should be specified on the root of the class hierarchy:

Defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy.

It is not specified by the specification if this annotation can be placed on a subclass and as such its behavior is undefined.

So to answer the question you have asked in the comments, if you have this hierarchy:

SubSub -> Sub -> Base

You only need to annotate Base with @Inheritance(strategy = TABLE_PER_CLASS) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM