Search code examples
javamongodbmorphia

Can Morphia cache query results to produce the same instance each time


Is it possible to get the same instance of an object when querying Morphia. This is the query which I am currently performing to find ServerInstances in my database.

Database.get().getDatastore().find(ServerInstance.class).field("_id").equal(id).get()

The Database.get().getDatastore() returns the Morphia datastore that I created earlier.

If I run the Query twice, both of the results are different. This is an issue, where I have used the original instance in a Map, for example. I have thought about updating the ServerInstance#equals(Object obj) method to match objects with matching ids, however this is probably not a good idea. There is also the fact that I update some @Transient fields on the first instance, meaning that both instances are no longer the same.

I have thought about creating a local cache for these objects, however the querying system used by Morphia is much nicer than having to write my own checks for matching objects.

Essentially, what I want to know is, if Morphia has it's own local caching system that I could use, or a better way to cache the objects so that I can continue to use the Morphia querying system.

Thanks in advance!


Solution

  • Morphia doesn't currently have a caching mechanism like that, no. Given the complexities of something like that, it's unlikely to make it in to morphia proper. You could front it with something like ehcache, though.