06 - Hibernate API

6.1 Overview

In this chapter, we will discuss API of the central components of Hibernate framework. Central components that we will discuss in this chapter are SessionFactory, Session and Query

6.2 Session Factory API

Session Factory can be obtained from Configuration object and is a heavyweight object and can be used with multiple threads as the session factory object is thread safe.

SessionFactory class is available under org.hibernate.SessionFactory package.

We would always need one instance of Session factory per database that our application is Interacting with. So if we have two different databases, we would create two session factory objects.

As Session factory is heavy weight object, creation of session factory object is expensive operation and recommended to get it created at application start up or can be accessed using JNDI

Use below code snippet to get a Session Factory object

     Configuration configuration = new Configuration().configure();

     SessionFactory sessionFactory = configuration.buildSessionFactory();

Once the session factory object is obtained, configuration object is no longer required.

Hibernate provides several methods of SessionFactory (can be referred from Hibernate Official Documentation ) but the most Commonly used APIs of SessionFactory are

  • close() – this method is used to destroy the session factory after releasing all the resources.
  • getCurrentSession()- this method is used to get the current session
  • getStatistics() – this method is used to get all the statistics of the session factory
  • isClosed() – this method is used to check is the session factory is closed or not
  • openSession()- this method is used to get or create a new session
  • openSession(Connection) – this method is used to get  or create a session using provided connection object. This method is not recommended.

 

6.3 Session  API

Session objects are created using Session factory and are a lightweight objects. Session objects provide a connection with a relational database.

By design, we should create a new session object when a database interaction is needed. A Session object represent a unit of work.

Session objects are not thread safe and hence should not keep open for a long time.

Use below code snippet to open a new Session object

            Configuration configuration = new Configuration().configure();

            SessionFactory sessionFactory = configuration.buildSessionFactory();

 Session session = sessionFactory.openSession();  

 Use session.close() to close the session.

We can pass an optional connection object as an argument to openSession() method if  we would want to interact with the database using associated connection. However, this approach is not recommended. 

Hibernate provides several methods of Session (can be referred from the Hibernate  Official Documentation ) but the most Commonly used APIs of Session are

  • beginTransaction() – this method is used to start a new transaction. New transaction object is returned by this method.
  • clear() – this method is used to clear the current session.
  • cancelQuery()- this method is used to cancel the current query execution.
  • close() – this method closes the session and release the resources.
  • connection() – we can get the connection associated with the session using this method.
  • contains(Object) – to verify if the given instance is associated with the session or not.
  • createQuery(String) – this method returns  a Query Object for the given HQL.
  • createSQLQuery(String) – this method returns SQLQuery instance of given SQL.
  • delete(Object) – this method deletes the row from the database associated with the given object.
  • flush() – this method flushes the session and updates the state of all associated instances.
  • get(Class, Serializable) -  this method returns the persistent object corresponding to the given identifier. If there is no persistent object corresponding to the identifier, it will return null.
  • getNamedQuery(String) – this method is used to get the instance of Query for the given named query defined in the mapping file.
  • getSessionFactory()- this method is used to obtain the session factory which is being used to get the session.
  • getStatistics()- this method is used to get the statistics of the session object.
  • getTransaction()- this method returns the associated transaction.
  • isConnected() – this method is used to check if the session is still connected.
  • isOpen()- this method is used to verify if the session is open or not.
  • isDirty()- this method is used to verify is there are changes pending to be updated in the database or not.
  • Load (Class, Serializable) – this method is similar to get () method, but it throws exception if the persistent object with a given identifier is not found.
  • Merge (Object) -  this method will assign a new reference to the given object.
  • refresh(Object)- this method loads the object again from database so in case the database state has been changed directly then object will be in sync of the database.
  • Save (Object) – this method saves the object to the database.
  • saveOrUpdate(Object) – this method either saves or updates the given object.
  • update(Object) – this method is used to reattach the detached object.

6.4 Query API

Query object is obtained using some of the session API and is used to execute the Hibernate Query Language (HQL).

  • executeUpdate() – this method is used to execute the delete or update statements on database and returns the number of affected rows.
  • list() – this method returns the result as list
  • Iterator () - returns the results as an iterator.
  • setBoolean(int , boolean) –  used to set the value of a given numbered placeholder.
  • setBoolean(Stirng, boolean)- used to set the value of a given placeholder.

(there are several setXXX available for different data types  similar to setBoolean)

  • setFirstResult( int ) -  we can specify the number from which  we would want to get the results.

 

6.5 Hibernate Object States

Classes whose instances are required to persist in the database are known as persistence classes. Any instance of persistent class can be in any one of the below three state.

  1. Persistent Object -  Persistent instances are the objects that are currently mapped with a  session and has a corresponding row in a relational database.
  2. Transient Objects-  Transient instances are the objects which are never associated with a session or with persistence context.
  3. Detached Objects-  Detached instances are the objects that are mapped to the session or persistent context but session is closed later. In other word, objects whose mapped session is closed

Like us on Facebook