Hibernate Tips: Calculate entity attributes with @Formula

Datetime:2016-08-22 23:33:09          Topic: Hibernate  DataBase           Share

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.





About List