Hibernate Session Management

By Eugenia Pérez | 14 June, 2015

There is some controversy about this topic and Hibernate reference documentation does not provide clear examples of best practices how-to’s. I have been researching on it for the last days and the result will be available within the next few weeks in one of the books I’m about to publish with Ra-Ma Editorial (based on Spring Framework and Hibernate).

Hibernate, as all we probably know, is an ORM mainly conceived for the Java platform. Hibernate provides a set of classes to deal with transactions and database connections, such as Configuration, SessionFactory and Session. A SessionFactory object is thread-saved, whereas a Session one is not. That is the main reason why a Session object has to be created and disposed each time a database access is performed.

However there’re two main approaches that can be possible. On one hand a new Session can be opened and closed each time a query needs to be sent to the database. On the other hand we can take advantage of applying the unit of work pattern. This design pattern is intended to make the most of database access regarding performance. This means that we have to wrap all the database operations we want to apply in a single transaction. For instance we can talk about a unit of work as all the operations generated as a consequence of a client request.

To sum up the unit of work pattern is the preferred one when talking about multi-threaded environments like a web application.

Assuming we are writing a console app a unit of work will be made up of several DAO operations. Taking place within the boundaries of a Hibernate transaction:

public static void main(String[] args) {
	GenericDAO productTypeDAO = new GenericDAO();
	Session sess = factory.openSession();
	Transaction tx = null;
	try {
		tx = sess.beginTransaction();
		ProductType pt = new ProductType(1, "Electronics");
		productTypeDAO.insert(pt);
		p = productTypeDAO.selectById(1, ProductType.class);
		tx.commit();
	}
	catch (RuntimeException e) {
		if (tx != null) tx.rollback();
		throw e; // or display error message
	}
	finally {
		sess.close();
}
facebooktwittergoogle_plusredditpinterestlinkedinmailby feather