Imagine having a tool that can automatically detect if you are using JPA and Hibernate properly.
Hypersistence Optimizer is that tool!
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.
Let’s assume that our application uses the following entity hierarchy:
To persist this entity hierarchy, we can use JPA inheritance, and, as explained in this article, the SINGLE_TABLE inheritance strategy is a very good default choice.
As its name suggests, the SINGLE_TBALE inheritance uses a single topic table to hold both base class and subclass entities belonging to this inheritance hierarchy:
For the next queries, consider e have the following 2 entities in the database:
Post post = new Post();
Announcement announcement = new Announcement();
One feature provided by JPA inheritance is the ability to fetch entities by their associated base class. This is called a polymorphic query, and the following query selects both the Post and Announcement entities:
If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.
The Criteria API provides many path expressions which allow you to build all sorts of entity queries dynamically. The type property of a given Path expression can be used to filter entities by their associated class.
Based on my book, High-Performance Java Persistence, this workshop teaches you various data access performance optimizations from JDBC, to JPA, Hibernate and jOOQ for the major rational database systems (e.g. Oracle, SQL Server, MySQL and PostgreSQL).
The SQL Master Class for Java Developers training is aimed to level up your SQL skills with techniques such as Window Functions, recursive queries, Pivoting, JSON processing, and many other database querying features supported by Oracle, SQL Server, MySQL, or PostgreSQL.