Hibernate Tips: How to downcast entities in JPQL queries
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.
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.
List<Object[]> result = em.createQuery( "SELECT a, p FROM Author a JOIN a.publications p WHERE treat(p AS Book).title LIKE '%Java%'") .getResultList();
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
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.
For completeness…
TREAT is a form of explicit downcasting. Hibernate also supports implicit downcasting. Taking your example query, the following is a valid query to Hibernate (and has been for a long time):
SELECT a, p FROM Author a JOIN a.publications p
WHERE p.title LIKE ‘%Java%’
Hibernate handles this as if the TREAT were specified. Obviously that makes the query non-portable to other JPA providers however.
Really cool stuff. Thanks Thorben for this wonderful post
Thank you for your kind words. I’m glad you like it 🙂
How about using SQL server views with hibernate 4.x ? Do I need to create hbm XML mapping file just like for a table?
Hi Wangdi,
in general, you can map database views like tables. But you might want to prevent any write operations on the entity that represents the view.
I explained that in more detail here: //thorben-janssen.com/hibernate-tips-map-view-hibernate/
Regards,
Thorben