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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
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.