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).  

Related Topics

Hibernate Inheritance Joined Table

In this inheritance strategy, mapping of the child class fields is done with the common fields of the parent class in a separate table. In other words, the common entities between the child...

3 minutes read.

Hibernate First-Level Cache

The first-level cache is related to the Session object. First level cache objects of one Session are not visible to the other Sessions, and all the cache data is lost when the Session...

2 minutes read.

Hibernate Criteria Query Language (HCQL)

Hibernate Criteria Query Language (HCQL) is mainly used for searching and fetching records. It works on the filtration rules and logical conditions. The Criteria interface, Restriction class, and Order class are available in...

4 minutes read.

Hibernate GeneratedValue Strategies

Hibernate GeneratedValue Strategies Hibernate supports some generation strategies to generate a primary key in the database table. We can access the strategy with the help of @GeneratedValue annotation. @GeneratedValue The @GeneratedValue annotation specifies how to...

3 minutes read.

Hibernate History and Versions

Next → History of Hibernate Hibernate was developed in 2001 by Gavin king with his colleagues from Circus Technologies. The main aim was to provide better persistence capabilities than those of EJB2, by reducing the...

2 minutes read.

Architecture of Hibernate

Next → Hibernate is an ORM framework with a layered architecture. It consists of many objects, such as a persistent object, sessionfactory object, transaction object, session, etc.  There are mainly three layers in Hibernate...

2 minutes read.

Hibernate One-to-Many Mapping

One-to-Many Hibernate Mapping Example In One-to-many association mapping, only one object of a persistent class is related to many objects of another persistent class. It is a relationship in which one (parent) is related...

3 minutes read.

Hibernate Second-Level Cache

The Second-level cache is related to the SessionFactory object. Once the SessionFactory is closed, all the second-level cache data associated with it will be lost. The cache manager will also get closed. Cache provider The...

5 minutes read.

Hibernate Query Language (HQL)

Hibernate provides its query language called Hibernate Query Language (HQL). HQL is an object-oriented query language, similar to the native SQL language, and it works with persistent objects. It is a database-independent and...

2 minutes read.

Hibernate first Example

Now we are going to create the first example in Hibernate. We will proceed step by step to develop the first Java application in Hibernate. The steps are listed below:- Create the POJO...

2 minutes read.

Hibernate Lifecycle

Hibernate Lifecycle In Hibernate, the mapped instances of the entity classes have a lifecycle. Either we can create a new object, or we can fetch the existing data from the database. The value objects do...

3 minutes read.

Hibernate Mapping

Hibernate Mapping Association- It means that two or more things are related to each other by some specific relation. In other words, it specifies how the objects are associated with each other. Hibernate mapping is one...

2 minutes read.

Hibernate Merge

Hibernate Merge Merge is a method available in Hibernate which is used to update the existing records. However, it creates a copy from the passed entity objects and returns it. In other words, the merge()...

2 minutes read.

Hibernate One-to-One Mapping Example

One-to-One Hibernate Mapping In One-to-One association mapping, one object of a persistent class is related to one object of another persistent class. Here, we are going to create an example of one-to-one mapping using...

3 minutes read.

Hibernate vs. JDBC

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

2 minutes read.

Hibernate Inverse

Hibernate Inverse An Inverse attribute is used to maintain the relationship between the parent and child class object. The inverse attribute is used only with bi-directional mappings such as one-to-many and many-to-many Hibernate mapping. In Hibernate, the...

2 minutes read.

Hibernate Caching

What is Caching? Caching is a process of saving data into the cache memory. A cache is a temporary storage layer which is used to increase the speed of data access. It allows...

2 minutes read.

Hibernate Many-to-Many Mapping

Many-to-Many Hibernate Mapping with Example In Many-to-Many association mapping, more than one objects of a persistent class are associated with more than one objects of another persistent class. For example, many (categories) are related to...

3 minutes read.

Hibernate Dialects

Hibernate Dialects Dialect is a Java class available in org.hibernate.dialect package, which helps to map Java Application with the database. To interact with the database, we need to define the required database dialect in...

2 minutes read.

Cascade in Hibernate

Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity whenever the state of its relationship owner (superclass) affected. When the relationship owner (superclass) is saved/...

3 minutes read.