Search code examples
javaandroidhibernateormidentity-map

Which Android/Java ORM uses “object caching” like Hibernate does?


I saw a bunch of questions about lightweight alternatives to Hibernate, especially for Android. But which of them has the “Identity Map” pattern?

This pattern makes sure that any object representing a row in the db exists only once in any session. – It helps my program to be consistent: if I change a mapped object somewhere, it is changed everywhere (because all references point to the same object). It doesn’t matter if I re-fetch the object via a new database query, or still have it around from earlier calls: the ORM makes sure they all behave like the same thing.

Hibernate does this in it’s “level 1 cache”.


Solution

  • ORMLite is an Android ORM package that as of version 4.26 (released on 9/26/2011) contains a first take on an internal object cache. ORMLite does not have a "session" pattern but the user can inject a cache into any DAO and can flush it whenever they choose. Here are the docs for the cache support.

    http://ormlite.com/docs/object-cache

    To quote from the manual, the cache supports the following things:

    • If you create an object using the DAO, it will be added to the cache.
    • When you query for an object using the DAO, if the object is in the cache it will be returned. If it is not in the cache then it will be added to the cache. This does not apply to the raw query methods.
    • If you update an object with the database using the DAO, if it exists in cache it will be updated.
    • If you refresh an object from the database using the DAO, if it exists in cache it will be refreshed.
    • If you delete the object using the DAO, the object will be deleted from the cache.

    There are 2 object cache implementations included with the ORMLite core package. One that supports weak/soft references and another that is a standard LRU.

    It is [obviously] a very simple implementation compared to Hibernate's level 1 cache. Feedback welcome.