Search This Blog

Hibernate/JPA Single Table Inheritance Example

In the previous article, we have discussed mapped superclass inheritance strategy. In this article, we will discuss The single table strategy which maps all entities of the inheritance structure to the same database table. This approach makes polymorphic queries very efficient and provides the best performance.

Note that when no explicit inheritance strategy is registered, Hibernate/JPA will choose the SINGLE_TABLE inheritance strategy by default.

SINGLE_TABLE inheritance performs the best in terms of executed SQL statements. However, you cannot use NOT NULL constraints on the column-level. You can still use triggers and rules to enforce such constraints, but it’s not as straightforward.

Creating Models + Hibernate/JPA Mappings

Each subclass in a hierarchy must define a unique discriminator value, which is used to differentiate between rows belonging to separate subclass types. If this is not specified, the DTYPE column is used as a discriminator, storing the associated subclass name.

The inheritance strategy is defined on the abstract superclass, using the @Inheritance annotation. In this example, we used InheritanceType.SINGLE_TABLE. This means all concrete subclasses will be stored in one table. You can optionally specify a discriminator column name. This column is registered by the @DiscriminatorColumn if omitted the default DTYPE name is used.

6. Create a Hibernate utility Class

Create a helper class to bootstrap hibernate SessionFactory. In most Hibernate applications, the SessionFactory should be instantiated once during application initialization. The single instance should then be used by all code in a particular process, and any Session should be created using this single SessionFactory. The SessionFactory is thread-safe and can be shared; a Session is a single-threaded object.

The bootstrapping API is quite flexible, but in most cases, it makes the most sense to think of it as a 3 step process:

Output

GitHub Repository

Conclusion

In this article, we have discussed the single table strategy which maps all entities of the inheritance structure to the same database table. This approach makes polymorphic queries very efficient and provides the best performance.