What is a Session? Can you share a session object between different theads?
Session: When we talk about the session then we can say that a session is used to get a physical connection with a database. The session object is light weight and designed to be instantiated each time an interaction is needed with the database. Persistent object are saved and retrieved through a session object.
Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession( ) method.
we can say that also the session object should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. The main function of the session is to offer create, read and delete operation for instance of mapped entity classes.
Instances may exist in one of the following three states at a given point in time:
transient: A new instance of a persistent class which is not associated with a session and has no representation in the database and no identifier value is considered transient by hibernate.
persistent: We can make a transient instance persistent by associationg it with a session. A persistent instance has a representation in the database, an identifier value and is associated with a session.
detached: Once we close the hibernate session, the persistent instance will ecome a detached instance.
In the given example we told that about the Session:
New Page 1Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
Read More →