Answer the question
In order to leave comments, you need to log in
Spring Boot Data JPA, how to add logic when reading object from database?
Hello!
There is an Entity that has an Integer field . I would like to add a check for the value that is raised from the database and some of my own logic. For example, if the database is null , write in the field 0 (zero).
I tried to add a setter and a constructor with this logic, but nothing worked, apparently Spring uses Reflection or some other curiosity :)
In principle, it would be possible to add a getter and give the program a value with substitution, but this field is the key for another one, which is ManyToOne, so this way is not suitable.
What can be done? Does Spring offer any way to solve this problem?
Answer the question
In order to leave comments, you need to log in
In general, I decided to add an additional service class that takes objects from the repository and transforms it as it should, and the main program already receives ready-made objects from it. What is right, because the transformation is already business logic and you don’t need to interfere with DAO. The most embarrassing thing is that this is the Spring Path and it is described in all textbooks. And I even blunted :) Well, nothing: understanding leads to memorization, next time I'll be smarter :)
Just specify the property for this column in the database: not null default 0
Create a method annotated with @PostLoad
But, I must warn you, your approach is not without its pitfalls.
If you turn null into 0, then the EntityManager immediately starts treating the record as changed. And when you exit the visibility zone, it will write it back to the database.
So you can get a big drop in performance and wonder for a long time "why everything slows down, I just subtracted the record!"
And further...
In principle, it would be possible to add a getter and give the program a value with a substitution, but this field is the key for another one, which is ManyToOne, so this way is not suitable.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question