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.
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?
Don’t want to read? You can watch it here!
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.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
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
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.