As already mentioned, it serves to delete a certain value from the JPA mapping and is useful in the case of calculated attributes.
To give an example of where this is useful, imagine that this value is something costly to obtain. As examples of these cases, I can cite this:
A value containing a total that has to be calculated when accessing several entities scattered in several tables.
The contents of a read disk file.
Some data that belongs to the entity but is not in the database, being obtained through a webservice.
Note that in all of these cases, if you force the getter to have to recalculate this every time, the performance will be bad. This could cause multiple queries to several tables in the database, or else multiple reads of a file, or perhaps multiple queries to some webservice.
Doing these things at the getter is not a good idea, and it’s better that all these things are computed in the processing of the business logic of the functionality in question and the getter just returns the result, even though few people expect a getter to be a method with a high complexity (because this is not usually good programming practice).
The Java language already has a modifier transient
to do this in fields, but it cannot be used for methods, if you are mapping in getters instead of in attributes. That’s why they invented the note @Transient
. In fact, the right one would be that the modifier transient
did not exist and its behavior was replaced by an annotation, but at the time it was conceived, there were no notes in Java yet.
As for the question of putting this in the entity and not in some other class, it is because the entity represents a concept of its domain with its respective business rules. It turns out that these resources that have to be computed are part of the business rule of the modeled entity, and therefore, there should be, otherwise, this would possibly be a violation of encapsulation.
The error (very common by the way) is to believe in the premise that the entity must reflect the database directly and imitate its structure, but this is not always true. Sometimes the entity format is not exactly the same as in the database.
And even if the format of the entity faithfully reflects the modeling of the database, add in the entity Venda
, an attribute totalVenda
that has the value resulting from the sum of the values of all the items of the sale, should not be something to disturb the JPA mapping.
I got it. That’s what I figured. I just don’t agree with the idea that the entity should not reflect the bank, but that’s a personal opinion and there’s no point in discussing it. Thank you for the reply!
– igventurelli