How to query by entity type using JPA Criteria API

Introduction Inspired by this Hibernate forum post, I decided to write an article to explain how you can filter by the entity type using Criteria API.

How to order entity subclasses by their class type using JPA and Hibernate

Introduction In this article, we are going to see how to order entity subclasses when executing a JPA query with Hibernate.

How to inherit properties from a base class entity using @MappedSuperclass with JPA and Hibernate

Introduction In this article, we are going to see how @MappedSuperclass can help us reuse the @Id mapping of a JPA and Hibernate entity so that it won’t have to be declared on each and every entity.

The best way to map the @DiscriminatorColumn with JPA and Hibernate

Introduction As previously explained, the SINGLE_TABLE inheritance is the most efficient entity inheritance strategy. However, for JPQL query such as this one: Hibernate generates a SQL query which filters by the associated discriminator column (e.g. DTYPE by default): So, because we are filtering by the discriminator column, we might want to index it or include it to speed up queries. However, the default STRING DiscriminatorType expects a VARCHAR column that must hold the longest entity subclass name. For the Announcement class, we need at least 12 bytes to store the entity class… Read More

The best way to use entity inheritance with JPA and Hibernate

Introduction Recently, my friend Lukas Eder wrote the following message on Twitter: Just like in any OOP (Object-Oriented Programming) language, entity inheritance is suitable for varying behavior rather than reusing data structures, for which we could use composition. The Domain Model compromising both data (e.g. persisted entities) and behavior (business logic), we can still make use of inheritance for implementing a behavioral software design pattern. In this article, I’m going to demonstrate how to use JPA inheritance as a means to implement the Strategy design pattern.

The best way to map the SINGLE_TABLE inheritance with JPA and Hibernate

Introduction Java, like any other object-oriented programming language, makes heavy use of inheritance and polymorphism. Inheritance allows defining class hierarchies that offer different implementations of a common interface. Conceptually, the Domain Model defines both data (e.g. persisted entities) and behavior (business logic). Nevertheless, inheritance is more useful for varying behavior rather than reusing data (composition is much more suitable for sharing structures). Even if the data (persisted entities) and the business logic (transactional services) are decoupled, inheritance can still help varying business logic (e.g. Visitor pattern). In this article, we are going… Read More