Hibernate / Hibernate Caching
How second level cache works in Hibernate?
Whenever hibernate session try to load an entity, it first looks for cached copy of entity in first level cache (associated with particular hibernate session).If cached copy of entity is present in first level cache, it is returned as result of load method.
If there is no cached entity in first level cache, then second level cache is looked up for cached entity.If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself.
If entity is not found in first and second level cache, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.
Second level cache validate itself for modified entities, if modification has been done through hibernate session APIs. If some user or process make changes directly in database, then there is no way that second level cache update itself until "timeToLiveSeconds" duration has passed for that cache region. In this case, it is good idea to invalidate whole cache and let hibernate build its cache once again.
More Related questions...