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.
The value of one of my entity attribute gets calculate by an SQL function. How can I map that with Hibernate?
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:
- 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.
- You need to provide a native SQL snippet to the @Formula annotation. This can affect the database portability of your application.
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.