Disabling EclipseLink cache

2019-04-30 19:40发布

问题:

In my application, when user logs in to the system the system reads some setting from DB and stores them on user's session. The system is performing this action by a JPA query using EclipseLink (JPA 2.0).

When I change some settings in DB, and sign in again, the query returns the previous results. It seems that EclipseLink is caching the results.

I have used this to correct this behavior but it does not work:

query.setHint(QueryHints.cache_usage,cacheUsage.no_cache);

回答1:

If you want to set query hints, the docs recommend doing:

query.setHint("javax.persistence.cache.storeMode", "REFRESH");

You can alternately set the affected entity's @Cacheable annotation

@Cacheable(false)
public class EntityThatMustNotBeCached {
...
}


回答2:

If you're returning a some kind of configuration entity and want to be sure that data is not stale, you can invoke em.refresh(yourEntity) after returning the entity from query. This will force the JPA provider to get fresh data from the database despite the cached one.

If you want to disable the L2 cache you can use <shared-cache-mode>NONE</shared-cache-mode> within <persistence-unit> in persistence.xml or use Cacheable(false) directly on your configuration entity.

If you're returning plain fields instead of entities and still getting stale data you may try clearing the PersistenceContext by invoking em.clear().