Motivation:
This article is useful if you need to calculate a non-persistent property based on the persistent entity attributes.
Description:
This is a Spring Boot application that uses the Hibernate, @Formula. Via this annotation, we can calculate non-persistent properties.
Key points:
Annotate the non-persistent property with @Transient
Annotate the non-persistent field with @Formula
As the value of @Formula, you have to add the eactly SQL query expression that calculates this non-persistent property based on the persistent entity attributes (check out the below discounted field):
Testing time:
Fetching a Book entity will be accomplished via the following SQL statement. Notice that Hibernate has added the formula given via @Formula is part of the query triggered against the database:
SELECT
book0_.id AS id1_0_,
book0_.isbn AS isbn2_0_,
book0_.price AS price3_0_,
book0_.title AS title4_0_,
book0_.price - book0_.price * 0.25 AS formula0_
FROM book book0_
Tam Ta Da Dam! :) The complete application is available on GitHub.
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices".
Comments