Hi all, my name is Chaitanya. I am reading Hibernate in action textbook and some online material and practicing. I read that SessionFactory is responsible to create the session objects.
What I understood is,
1. It is like a pool (same like connection pooling mechanism), once we ask for a new session object, hibernate checks the session factory for any available sessions. If there is a free session object we will get that session. If not hibernate creates a new session and return it to us. Once we finish our work the session is returned to the SessionFactory.
2. It acts like a cache. In a web application environment, suppose if we load a table using the session(for first time) and after our business logic is executed the session is returned to the SessionFactory. Now if someone asks for the same table, hibernate will return the session which has the table, from the SessionFactory instead of querying the database.
This is what I understood, I believe that I am not fully correct in my understanding. Besides I have a doubt. What if I close the session?
When I close the session, I think SessionFactory will not cache the table. If this is true we should not close the session object.
Can anyone tell me whether my understanding about the SessionFactory is correct or not.
There are two level of cache in Hibernate. First level cache and second level cache.
Hibenate uses Session as first level cache by caching the fetched object into Session.
When you ask for the same object with same identifier in a session , hibernate will not try to fetch it from database , it will pick the object from session itself.
In this way hibernate gives you repetable read for free.
SessionFactory is used for second level cache and in order to use second level cache , you have to explicity enable second level cache.
In second level cache , you can cache query result, queries and provide expiration time when hibernate should update the cache when it is asked to provide data from the cache again.