Reputation: 2728
I am new to Hibernate and was reading about Hibernate First Level Cache.
I have a doubt.
Will every session that is associated with the SessionFactory have an individual cache or for all the sessions there will be only one cache?
Can anyone please explain this .
Upvotes: 1
Views: 2975
Reputation: 1568
The first level cache is associated with Session object. As we know session object is created on demand from session factory and it is lost, once the session is closed. Similarly, first level cache associated with session object is available only till session object is live. It is available to session object only and is not accessible to any other session object in any other part of application.
Some Important Points:
First level cache is associated with “session” object and other session objects in application can not see it.
The scope of cache objects is of session. Once session is closed, cached objects are gone forever.
First level cache is enabled by default and you can not disable it.
When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session.
If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.
The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method.
The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.
Quoted from: http://howtodoinjava.com/2013/07/01/understanding-hibernate-first-level-cache-with-example/
Upvotes: 4