GAE, JDO: working with entities loaded from cache
-
26-06-2021 - |
Pregunta
I use simple layer for loading and storing entities by key or id and I just added caching to this layer. When entity with given key is in the cache, return it rather then fetch from the datastore. And when the entity is updated and saved to datastore, the layer simply sets the entity in the cache to null. It's completely transparent.
It seems to be working fine, however the object fetched from the cache is slightly different from the object fetched from the datastore. Some things stopped working, for example and I can't use .contains() on Collections inside entity to check whether there is a relationship between two entities. I also encountered a weird behavior, when I loaded an object from cache and immediately after that stored to the datastore, all items in collections representing relationships were replaced with null
s. However I couldn't reproduce it. Now it's working fine.
I don't know what's happening under the hood, so the question is, is this way of working with cache reliable? Can I work with entities fetched from cache just like as they were fetched from the datastore (accessing children, updating, removing...)?
Solución
Two things to note:
All objects stored to Memcache get serialized/deserialized, meaning their memory representation is taken and changed into a series of bytes (and vice versa).
Collection.contains(object)
usesobject.equals(anotherObject)
to check if collection contains certain object. By defaultObject.equals()
is onlytrue
if this is the exact same object (= object at the same memory location).
Given that: serializing object and then deserializing it will never make an object that gives deserialisedObject.equals(originalObject) == true
.
If you really need this, than you should override .equals()
(and also .hashCode()
) in the class you store in Memcache, so that you actually compare meaningful values inside the Class (= compare values of all fields).