Take your skills to the next level!
The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, monthly Java Persistence News, monthly coding problems, and regular expert sessions.
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?
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.
List<Object> result = em.createQuery( "SELECT a, p FROM Author a JOIN a.publications p WHERE treat(p AS Book).title LIKE '%Java%'") .getResultList();
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
Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.
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.