W
W
Wan-Derer2021-05-27 16:21:11
Java
Wan-Derer, 2021-05-27 16:21:11

Hibernate how to initialize calculated field in Entity?

Hello!
I have an @Entity class. The fields in it are filled from the database using Hibernate.
I want to add a field to this class that is not in the database and is calculated based on other fields. Accordingly, I need all the fields to be picked up from the base before I start calculating my value. How to do it? Maybe there is some annotation on this account, or some other technique?

PS: so far I have only thought of making a wrapper over the @Entity class, in which I will receive the object and set the field (or make the field in the wrapper itself). But I don't really like this way...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-05-27
@Wan-Derer

Good afternoon!

I want to add a field to this class that is not in the database

I suspect you need to do the following:
1) create a field with an annotation @Transient
For example,
@Transient
private long calc;

https://stackoverflow.com/questions/2154622/why-do...
This way this field will not be stored in the DB.
...which is calculated based on other fields.

2) Add an annotation to this field @Formula
https://thorben-janssen.com/hibernate-tips-calcula...
Read this article - https://vladmihalcea.com/how-to-map-calculated-pro.. Another option is to follow point 1.
But instead of using an annotation, @Formulacreate a method with an annotation @PostConstructand then initialize your field with the desired value

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question