Reputation: 2093
Hibernate stores cached entities as instances of CachedEntry
class which means that every time an entity is requested from the second level cache, a new instance of that entity is created from the data contained in CachedEntry
.
In most cases, this is a good approach because it prevents the cached data from being accidentally modified by code which requests the entities. But when the stored entities are immutable, this cannot happen.
We have a bunch of entity objects which contain quite large data (have a lot of attributes), and once written, they can never change, hence the entity objects are immutable.
Is there a way to force Hibernate to store immutable objects as "actual instances" meaning that for each distinct entity, only one immutable instance would exist in the cache which would always be returned, instead of creating new instances all the time?
I would expect Hibernate to have this behavior with objects annotated with @Immutable
, but that's not the case.
Upvotes: 1
Views: 931
Reputation: 23552
It is not possible to do it in Hibernate for immutable objects (entities) either, for multiple reasons, mostly concerning associations:
Suppose that an immutable object has an associated collection (of immutable entities also). That collection can be lazy, meaning that the object is effectively mutable after all. The same is true for lazy to-one mappings.
Cache eviction and expiration policies would be hard to define. If an entry expires or is evicted from its cache region, what to do with references to that object in other entities that are still in the cache?
Storing entities to cache would be more expensive operation as it would involve storing the entity and all of its loaded associations (each to its own cache region), and checking which parts of the graph are already in the cache.
Working with detached entities of this kind would be difficult with the current Hibernate internals.
Underlying cache provider would store only references to objects. It would not be able to extend cache content to disk, off heap or compress it for better memory management.
These are the reasons that first came to my mind and there are probably many other obstacles that would make it hard for Hibernate to achieve this.
You can find more info about Hibernate second-level cache in this blog and of course in the official documentation.
Upvotes: 1