It offers various functions such as create, delete, get, update to operate on the database by using session methods that exist in four states namely: Transient, Persistent and Detached, Removed. Hibernate has created to serve this purpose. It smoothly connects the database to java language irrespective of any database.
The SessionFactory is a thread safe object and used by all the threads of an application. A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database.
SessionFactory is an Interface which is present in org. hibernate package and it is used to create Session Object. It is immutable and thread-safe in nature. buildSessionFactory() method gathers the meta-data which is in the cfg Object. From cfg object it takes the JDBC information and create a JDBC Connection.
Spring opens a new Hibernate Session at the beginning of the request. These Sessions are not necessarily connected to the database. Every time the application needs a Session, it will reuse the already existing one.
Think of Hibernate's Contextual Session
as a mapping of a current Session to a user's Context.
For example: a single transaction could be such a context, hence if the Hibernate Session's lifecycle matches a life of this transaction, the Session could be called contextual, where a single transaction defines such a context
. Sometimes this particular case is labeled as a session-per-request
model.
A Hibernate interface CurrentSessionContext is there to map a current session ( e.g. SessionFactory.getCurrentSession()
) to different contexts. This interface has 3 implementations:
JTASessionContext: current sessions are tracked and scoped by a JTA transaction. The processing here is exactly the same as in the older JTA-only approach. See the Javadocs for details.
ThreadLocalSessionContext: current sessions are tracked by thread of execution. See the Javadocs for details.
ManagedSessionContext: current sessions are tracked by thread of execution. However, you are responsible to bind and unbind a Session instance with static methods on this class: it does not open, flush, or close a Session
Take a look at the Architecture Current Session part of the Hibernate documentation for more "official" details.
Another very good link explaining the concept of Hibernate Contextual Session
http://relation.to/2037.lace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With