Hibernate Session Interface

Hibernate Session Interface

A Session is an interface between the Java application and the Hibernate. It is available in the org.hibernate.session package. It should not be kept open for a long time, as it is not threadsafe and a short-lived object. A Session instance can be obtained through SessionFactory interface. It is a lightweight object and holds the first-level cache data in Hibernate.

Whenever there is a need for database interaction, a session object is called. The main aim of the Session is to provide communication between the Java application and the database. Session objects are used to execute CRUD (Create, Read, Update, and Delete) operations for the objects of the mapped entity.

Objects may exist in one of the following states:

  • Transient- An object is said to be transient, if it is initialized using the new operator, and it is not associated with any Hibernate Session. A transient object has no persistent representation and has no identifier value. To make an object persistent, we use Hibernate Session. A transient object may be made persistent by calling save(), persist() or saveOrUpdate() functions.
  • Persistent- A persistent object has a representation in the database, an identifier value, and it is also associated with a Hibernate Session. In this state, Hibernate will detect changes made to an object and synchronize it with the database. A persistent object may be made transient by calling delete() function.
  • Detached- When the session of a persistent object has been closed, the object will be known as a detached object. The detached object can be reattached to a new session when needed. A detached object may be made persistent by calling update(), saveOrUpdate(), lock() or replicate() functions.

The below code shows the initialization of session:

Session sess = factory.openSession();
 Transaction tx; 
 try { 
  tx = sess.beginTransaction(); 
  //do something... 
  tx.commit(); 
 } 
 catch (Exception e) {
  if (tx!=null) tx.rollback();
  throw e;
 } 
 finally {
  sess.close();
 } 

Methods of Session Interface

Session interface provides a variety of methods. Some commonly used methods are listed below:

Methods Description
public Transaction beginTransaction()                                    This method returns the associated transaction object when a unit work is done. If there is no transaction available, then it begins a new transaction.
public void cancelQuery()   This method is used to cancel the execution of the current query. It is the only method of Session which can be safely called from another thread.
public void clear() This method is used to clear the session completely.
public Connection close()   This method is used to close the connection or end the session. It is not always necessary to close the session.
public Criteria createCriteria(Class persistentClass) This method is used to create a new Criteria object, for the given persistent class or a superclass of a persistent class.
public Criteria createCriteria(String entityName) This method is used to create a new Criteria object, for the given entity name.
public Query createQuery(String queryString) This method is used to create a new object of Query for the given HQL query string.
public void delete(Object object)   This method is used to remove a persistent object from the database. It cascades to associated objects if the association is mapped with cascade=”delete.”
public void delete(String entityName, Object object) It performs the same functions as to delete(Object object).
public Serializable getIdentifier(Object object)   This method is used to return the identifier value of the given entity associated with the Session. If the associated object is transient or detached, an exception is thrown.
public Session getSession(EntityMode entityMode)   This method is used to open a new Session with the given entity mode. Here, entityMode is used for creating a new Session. This new Session inherits the Connection, Transaction, and other information from the existing Session.
public SessionFactory getSessionFactory() This method is used to get the Session factory, which has created the current Session.
public Transaction getTransaction()   This method is used to get the transaction object associated with the current Session.
public void persist(Object object)   This method is used to make a transient object persistent. It cascades to associated objects if the association is mapped with cascade=”persist.”
public void persist(String entityName, Object object) It performs the same functions as to persist(Object object).  
public void setFlushMode(FlushMode flushMode) This method is used to set the flush mode for the current session. A flush mode defines the points at which the Session is flushed.
public void update(Object object)   This method is used to update the persistent object with the identifier of the given detached object. If there exists a persistent object with the same identifier, an exception is thrown.
public void update(String entityName, Object object) It performs the same functions as to update(Object object).