Hibernate Inheritance Mapping
By AmarSivas | | Updated : 2021-07-21 | Viewed : 252 times

A detailed tutorial explains the Hibernate Inheritance Mapping. Let\'s start the div into the concept.
Table of Contents:
Hibernate Inheritance Mapping
Inheritance mapping is nothing using the inheritance in hibernate for applying curd operation with the database. Hibernate does support inheritance even databases do not. We will see different Inheritance strategies supported by Hibernate.
Hibernate Single Table Inheritance
Singe table inheritance is also called Table per hierarchy. In this Single table inheritance, all the subclasses map to one table which means all types of records will be stored in one database table. Here database table contains one column called the discriminated column.
Notice below the given diagram to represent the relationship between the entity classes. We will use the same relationship for Single table inheritance.

Syntax of Single table inheritance
@Entity
@Table(name = "book_1")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="BOOK_TYPE",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="Book")
public class Book {
}
@Entity
@DiscriminatorValue("FictionBook")
public class FictionBook extends Book{
}
@Entity
@DiscriminatorValue("NonFictionBook")
public class NonFictionBook extends Book{
}
When you execute the save operation with hibernate with the above-given entity classes then only the table will represent all these three entities.
Hibernate Inheritance Table Per Subclass
In this Table per subclass mapping, each subclass maps to a different table. When we insert the entry of subclass in the respective table then the referenced entry will be added to the parent class.
Syntax of Table per subclass
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="BOOK_2")
public class Book {
}
}
@Entity
@PrimaryKeyJoinColumn(name="BOOK_ID")
@Table(name="fiction_book2")
public class FictionBook extends Book {
}
@Entity
@PrimaryKeyJoinColumn(name="BOOK_ID")
@Table(name="nonfiction_book2")
public class NonFictionBook extends Book {
}
Hibernate Inheritance Table per Class
In this inheritance Table per concrete class, each subclass represents a separate table.
Syntax of Table per Class
@Entity
@Table(name = "book_3")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Book {
}
@Entity
@Table(name="fiction_book3")
public class FictionBook extends Book{
}
@Entity
@Table(name="nonfiction_book3")
public class NonFictionBook extends Book{
}
In this inheritance mapping, each insertion of each entity will create separate record in a different table. Here three records will be getting stored in three tables.
Please refer to the code for all three types of inheritance mappings in the GitHub repo.