Managing the cache

Besides configuring the cache in your setting files, you can further modify the cache behavior in the code. This is important because in some cases, you would like to bypass the cache completely or force the cache to expire. We will discuss these cases here.

Remove cached entities

In some cases, you want to force the eviction of a cached entity because you may know at some of point of your program execution you will end up with stale data. You can evict entities from both the first-level cache and the second-level cache.

The API to evict entities from the first-level cache is through the session object, that is, session.evict(). You should note that if the cached entity has been modified during the session, the changes would not be pushed to the database when the session is flushed.

Similarly, the second-level cache provides the interface to evict a cached entity. The Cache class offers this API. (This used to be under SessionFactory, but it has been moved, so you first have to obtain Cache from sessionFactory.getCache() and then call evict.) The API to remove cached entities from the second-level cache is quite rich. You can remove an entire region by type (Entity, Collection, or Natural ID), or by region name.

Cache modes

Hibernate offers ways to modify the second-level cache behavior that is declared by your configuration settings. Setting the cache mode on the session object is the way you change the behavior.

In fact, in the same session while it's open, you can modify its cache mode as many times as you wish. (You don't have to close the session to do this.)

Consider the following code:

session.setCacheMode(CacheMode.IGNORE);
Person person = (Person) session.get(Person.class, personId);
…    
// evict the person from first level cache
session.evict(person);
session.setCacheMode(CacheMode.NORMAL);
…
person = (Person) session.get(Person.class, personId);

By setting the session cache mode to IGNORE, the first call to get the session will cause a database hit. If we evict this entity from the first-level cache and set the mode back to NORMAL, the next time that we ask for the same person entity, it will fetch from the second-level cache if it's present there.

Remember that the session cache mode only affects the second-level cache. Besides IGNORE and NORMAL, there are other useful modes, which are well documented in the JavaDocs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.32.1