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.
I often need to provide a value that gets calculated based on an entity attribute, like the age of a person. How can I cache this calculated attribute in the entity without storing it in the database?
Don’t want to read? You can watch it here!
There are different ways to provide a calculated value to the user of the entity:
- You can use a @Formula to provide an SQL expression which returns the value.
- You can use field access and calculate the value in a getter method.
- You can use a transient entity attribute which stores calculated value without persisting it in the database.
I already explained option 1 in a previous post and will, therefore, focus on option 2 and 3.
Calculate in a getter method
Option 2 is easy to implement. When you use field access, you can add additional getter methods to your entity. You can for example, add a getAge() method that calculates and returns the age of the Author.
This approach requires you to calculate the value for each call of the getAget() method and is, therefore, not a good solution for complex calculations.
Transient entity attributes
The transient attribute approach requires a little more code but allows you to store the calculated value in an entity attribute without persisting it. The @Transient annotation tells Hibernate, and any other JPA implementation, to ignore the attribute when writing or reading the entity. You can, therefore, use it in your getAge() method to store the calculation result after it was calculated. This can be useful, if you need to perform a complex calculation that you don’t want to repeat for each call.
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.
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.