Jardo Jardo - 1 year ago 63
Java Question

Are objects stored in Hibernates 2nd level cache guaranteed to be "immutable"?

I was wondering what would happen, if I change a property of a DOM object retrieved from Hibernates second level cache. I found this quote:

2nd level cache stores a map of entities' IDs to other properties (it doesn't actually store objects, but the data itself)

in this answer: http://stackoverflow.com/a/7059822/2468620.

This should mean that when I retrieve an entity from second level cache, it is "freshly" created from the stored raw data. Therefore if I change properties of this entity, it shouldn't affect the data stored in second level cache. That meaning when I retrieve the entity again in another session, its properties should not be affected by the described change.

For examle:

user = userDao.find(1); // get user stored in second level cache

System.out.println(user.getName()); // returns "originalName"


// === this is done in a different session ===

user = userDao.find(1);

System.out.println(user.getName()); // should return "originalName"

I tried the above example with eh-cahce and it really works but my question is:

Is this behavior guaranteed? I mean if I can depend on it even when I change the cache provider, or when the implementation of my used cache provider changes? I looked in the JPA specification and didn't find information on this.

Answer Source

Yes it is. The second level cache gives you a "copy" of the cached entity data.

The entity is not stored as-it-is. An entity must be dehydrated before being stored to the cache. When you load an entity from the cache, the entity is rehydrated back, so you always get a new copy of the dehydrated data.

As opposed to a java.util.concurrent.ConcurrentHashMap, the second level cache could be saved to the disk (meaning you always get a copy of the disk-based saved data), and so it must be consistent with both an in-memory and a disk-based 2nd level caching implementation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download