Search code examples
javacachingeclipselink

@Cache in EclipseLink


I want an in-time got objects from database. I decided not to permit caching of my entities. By using this configuration:

@Cache(
        type = CacheType.NONE/*,
        alwaysRefresh = true,
        disableHits = true,
        coordinationType = INVALIDATE_CHANGED_OBJECTS*/
)

But I have read the documentation here that:

NONE

public static final CacheType NONE
WARNING: Does not preserve object identity and does not cache objects.

Is that warning important, I may understand that JVM may misrelate objects to their real identities! Is there any suggestion for having the best configuration of not caching an object like playing with alwaysRefresh for example.


Solution

  • If your program is the only application that uses the database you should not disable caching, if there are multiple clients it may be correct to disable caching, or reconfigure caching.

    As with any caching strategy the tradeoff is between speed and stale data. Most JPA implementations share a (2nd level) cache between the Persistence Contexts (the PC can be though of a 1st level cache), so when you load an entity using em.find() there is no need to access the database if the instance is already cached. If another client has access to the database you may end up serving stale data if the database was modified.

    If your have a clustered JPA application, and the database is only accessed by your JPA applications, you can still use caching, as long as you configure cache-coordination. When cache-coordination is used, one instance will inform the others if an entity was updated, so the other instances can update their cache, or discard their cached version.

    In the solutions I have built I have almost always had to disable caching, because the database has multiple clients, and we never wanted to display stale data.