Sasha Salauyou Sasha Salauyou - 6 months ago 18
Java Question

Any way to inherit an entity which is not @MappedSuperclass?

Let's suppose I have a JPA entity:

@Entity
@Table(name = "PARENT")
public class Parent {
// ...
}


Is there any way, maybe Hibernate-specific, to create subclass of
Parent
in a separate table?

@Entity
@Table(name = "CHILD")
public class Child extends Parent {
// ...
}


The main idea is to have set of common entity classes in a base package shared among projects, and extend them only if some project-specific properties are required.

Answer

Hibernate Inheritance: Annotation Mapping

Annotate the parent class with @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS). The Hibernate docs (for version 4.3, the new 5.0 docs seem to be missing this section so far) cover this in Chapter 10 and section 5.1.6 of the manual.

In One Table per Concrete class scheme, each concrete class is mapped as normal persistent class. Thus we have 3 tables; PARENT, CHILD to persist the class data. In this scheme, the mapping of the subclass repeats the properties of the parent class.

Following are the advantages and disadvantages of One Table per Subclass scheme. Advantages This is the easiest method of Inheritance mapping to implement.

Following is the example where we map Parent and Child entity classes using JPA Annotations.

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

    // Getter and Setter methods, 
}

@Inheritance – 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.

@InheritanceType – Defines inheritance strategy options. TABLE_PER_CLASS is a strategy to map table per concrete class.

@Entity
@Table(name="Child")
public class Child extends Parent {

    // Getter and Setter methods, 
}