Hibernate Tips: How to downcast entities in JPQL queries

By Thorben Janssen

Jpql, Query

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.

entity model

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







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.

Get it now!



Tags

Jpql, Query


About the author

Thorben is an independent consultant, international speaker, and trainer specialized in solving Java persistence problems with JPA and Hibernate.
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70 solutions to common Hibernate problems.

Books and Courses

Coaching and Consulting

Leave a Reply

Your email address will not be published. Required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  1. 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.

    1. 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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}