[Solved] Hibernate Program Not Terminating With Examples

Recently I was writing a small hibernate program and noticed that the program was not terminating even though main method is executed successfully. I was using Hibernate latest version 4.3.5.Final.

Hibernate Program Not Terminating Program

My sample class code is shown below.


package com.journaldev.hibernate.main;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.journaldev.hibernate.model.Employee1;
import com.journaldev.hibernate.util.HibernateUtil;
public class HibernateMain {
	public static void main(String[] args) {
		Employee1 emp = new Employee1();
		emp.setName("Lisa");
		emp.setRole("Manager");
		emp.setInsertTime(new Date());
		//Get Session
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.getCurrentSession();
		//start transaction
		session.beginTransaction();
		//Save the Model object
		session.save(emp);
		//Commit transaction
		session.getTransaction().commit();
		System.out.println("Employee ID="+emp.getId());
	}
}

The problem with above code is that Hibernate doesn’t release the resources and it’s our responsibility to release the resources once we are done with it.

As you can notice that in above program, ServiceManager instance is created but not closed.

So I changed the program to below code and the program started terminating fine after the main method is executed.


package com.journaldev.hibernate.main;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.model.Employee1;
import com.journaldev.hibernate.util.HibernateUtil;
public class HibernateMain {
	public static void main(String[] args) {
		Employee1 emp = new Employee1();
		emp.setName("Lisa");
		emp.setRole("Manager");
		emp.setInsertTime(new Date());
		SessionFactory sessionFactory = null;
		Session session = null;
		Transaction transaction = null;
		try{
		//Get Session
		sessionFactory = HibernateUtil.getSessionFactory();
		session = sessionFactory.getCurrentSession();
		//start transaction
		transaction = session.beginTransaction();
		//Save the Model object
		session.save(emp);
		//Commit transaction
		transaction.commit();
		System.out.println("Employee ID="+emp.getId());
		}catch(Exception e){
			System.out.println("Exception occured. "+e.getMessage());
		}finally{
			if(session.isOpen()){
				System.out.println("Closing session");
				session.close();
			}
			if(!sessionFactory.isClosed()){
				System.out.println("Closing SessionFactory");
				sessionFactory.close();
			}
		}
	}
}

Notice that I am closing resources in finally block, so that even if application throws any exception all the resources are released.

By admin

Leave a Reply

%d bloggers like this: