SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); //perform hibernate operations... session.close(); sessionFactory.close();
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = null; try { session = sessionFactory.openSession(); //perform hibernate operations... } catch (HibernateException e) { throw new RuntimeException("Error during Hibernate operations", e); } finally { if (session != null) { session.close(); } if (sessionFactory != null) { sessionFactory.close(); } }In this example, we created a session as in the previous example. However, we have also included a try-catch block to catch any Hibernate exceptions that might occur while performing the operations. In the finally block, we are closing the session and the `SessionFactory` explicitly, but we are also checking whether they are null or not before closing them. The `org.hibernate` package library is used for Hibernate, an object-relational mapping framework for Java.