问题
I have the requirement to keep track of a field of a persistent entity, which will be changed very often and is not really a feature of that entity, rather some kind of caculation. Sometimes, a user wants to see that calculation, but this case is very rare (once month or so). So the result of this calculation has to be saved somehow, but i want to avoid to save it in the database every time it changes, because this would trigger an update event of the parent entity each time (which would create unnecessary database transactions, user notifications etc).
A first idea to solve this issue was to make the field transient, but to save it in the second level cache of hibernate. I didn't find a way to do so when looking in the documentation, but maybe i oversee a hidden possibility. So do you know whether and how this is possible?
(I have other possibilities to solve this issue, e.g. using the data grid of the container, in my case Infinispan of JBoss - but that would require a different solution for every application server. I just want to make sure whether the above-mentioned solution, which would be independent from the container, could be an alternative)
回答1:
If the calculation is an SQL function, you could use a @Formula (instead of calculating in the application and storing).
Regarding the 2nd level cache, no, transient fields are not cached. Caching (and ORM in general) is based on persistent objects/properties and their metadata. By definition, transients are ignored completely.
来源:https://stackoverflow.com/questions/19677370/hibernate-is-it-possible-to-save-a-transient-field-in-second-level-cache