Hibernate Tips: Calculate entity attributes with @Formula

By Thorben Janssen

Mapping

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:

The value of one of my entity attribute gets calculate by an SQL function. How can I map that with Hibernate?

Solution:

You can use the @Formula annotation to provide an SQL snippet which Hibernate will execute when it fetches the entity from the database. The return value of the SQL snippet gets mapped to a read-only entity attribute.

I use the annotation in the following example to calculate the age of an author.

When Hibernate fetches an Author entity from the database, it adds the SQL snippet of the formula annotation to its SQL statement.

The @Formula annotation provides an easy way to map the result of an SQL snippet to an entity attribute. But it also has some downsides you should be aware of:

  1. Hibernate executes the SQL snippet for every Author entity it fetches from the database. So better make sure, that you only use it for attributes you need in all of your use cases.
  2. You need to provide a native SQL snippet to the @Formula annotation. This can affect the database portability of your application.


 

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 as a paperback, ebook or PDF.


Tags

Mapping


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 Repl​​​​​y

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.

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