Monday, February 23, 2009

The Cache in Hibernate!

Hibernate has two kinds of cache, which are the first-level cache and the second-level cache. The first-level cache aka "session cache", and the second-level cache aka "process-level cache".

The first-level cache is mandatory and can’t be turned off; However, the second-level cache in Hibernate is optional. Because the process-level cache caches objects across sessions and has process or cluster scope, in some situation, turning on the process-level cache can improve the performance of the application. In fact, before accessing the database to load an object, Hibernate will first look in the Session cache and then in the process-level cache.

The process-level cache is best used to store objects that change relatively infrequently, and it is set up in two steps. First, you have to decide which concurrency strategy to use. After that, you configure cache expiration and physical cache attribtes using the cache provider.

Hibernate supports a variety of caching strategies including:

read-only : which is suitable for objects which never changes. Use if for reference data only.
read-write : which is suitable for objects that are modified by the application.

To cache these classes in the process-level cache, we must use the <cache> element in the O/R mapping.

No comments: