Hibernate caching

244 Views Asked by At

In hibernate already First level Cache is available for caching then why we have to use Second level cache? Instead of second level why we can not use only First level cache in hibernate for caching?

3

There are 3 best solutions below

0
On

First level cache works at Session level, It means that a persistent object will be tracked until current Session is closed. And any changes made on this object before closing this session will be reflected in database. It's enabled by default.

Second level cache works at SessionFactory level, So all the changes made on a persistent object will be tracked even if current session is closed. You have to manually enable it. There are a few vendors which provide this functionality, Some of them are ehCache, SwarmCache, OScache etc.

0
On

Hibernate second level cache is an optional cache and first level cache will always be consulted before any attempt is made to locate an object in second level cache.

It is mainly used when you have the requirement for caching an object across sessions.

1
On

See What are First and Second Level caching in Hibernate? for good descriptions on Hibernate caching.

Basically:

  • the first level cache speeds up updates to a single session/transaction
  • the second level cache speeds up retrieval of objects used in many transactions.

These are two distinct use-cases with different requirements that needs different kinds of logic.