Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.

Question:

My entity model contains an inheritance structure, and I need to limit my query to a specific subclass. How can I do that with JPQL?

Solution:

JPA 2.1 introduced the TREAT operator to JPQL which you can use to downcast an entity within your query.

You can, for example, create an entity model with Authors who have written different kinds of Publications, like Books and BlogPosts. It’s pretty obvious that Publication is the super class of Book and BlogPost and that you have to model a relationship between Author and Publication.

You can now use the TREAT operator to downcast the Publications to Books and select all Authors who have written a Book about Java. The following code snippet shows an example of such a query.





Learn more:

The TREAT operator is just one of several interesting new features introduced in JPA 2.1. You can get an overview of the different features and links to more detailed tutorials in JPA 2.1 – 12 features every developer should know.

Hibernate Tips Book