The Dodo
The Dodo

Reputation: 147

EhCache does not update cache

I'm using EhCache v2.3.0 in combination with EclipseLink v2.5.2 and EJB 3.0 in an Enterprise Application.

The problem is, that the object of EhCache is not updated. The expected behaviour is, that the cache expires after 60 seconds and reloads the data. What actually happens is, that the cache expires after 60 seconds and reloads the old data.

This happens even though the entity cache is set to 'isolated'. For test purposes, I even set the cache type to none, but it doesn't work.

Has anybody an idea?

Here is the ehcache.xml:

<ehcache name="testCache">
<defaultCache
    timeToIdleSeconds="60"
    timeToLiveSeconds="60"/>
<cache name="myCache"
    timeToIdleSeconds="60"
    timeToLiveSeconds="60"/></ehcache>

This is load properly at the startup in the Context-Listener. So the cache is set up with the correct values, I've checked in debug-mode.

After the Cache got initilized (it's an Singleton), it's accessed with this method:

/*
This method returns the current values in the cache as an list. 
If the elements expired, it gets the new values from the database, puts them into the cache and return them as list.
*/

public List<CacheEntries> getEntries() {

EhCache cache = cacheManager.getEhCache("myCache"); 
cache.evictExpiredElements();
List<CacheEntries> list = new ArrayList<CacheEntries>();

if(cache.getSize() == 0) {
    //get CacheEJB
    list = cacheEjb.getAll();
    for(CacheEntries e : list) {
        cache.put(new Element(e.getName(), e));
    }
}
else {
    Element element = null;
    List<String> keys = cache.getKeys();
    for(String s : keys) {
        element = cache.get(s);
        list.add((CacheEntries) element.getValue());
    }
}
return list;

}

Thus the entity is annotated:

@Entity @Cache(type = CacheType.NONE, isolation = CacheIsolationType.ISOLATED) @Table ...

Upvotes: 4

Views: 1952

Answers (1)

Paul Wasilewski
Paul Wasilewski

Reputation: 10372

The cause of this problem is not EhCache it's the second-level cache of JPA. To disable the whole JPA cache add to your persistence.xml

<persistence-unit name="ACME">
   <shared-cache-mode>NONE</shared-cache-mode>
</persistence-unit>

And if you want to disable the cache for a specific entity use @Cacheable(false) as class annotation on your entity.

Also consider not to use CacheType.NONE.

Note, the CacheType NONE on the @Cache annotation should not be used to disable the cache, instead shared should be set to false. [EclipseLink/Examples/JPA/Caching]

As last option try to trigger a cache refresh by a query hint.

Query query = em.createQuery("Select e from Employee e");
query.setHint("javax.persistence.cache.storeMode", "REFRESH");

Upvotes: 2

Related Questions