Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); // perform database operations tx.commit(); session.close();
Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); // perform database operations tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { session.close(); }In this example, we use the getTransaction method to start a new transaction associated with the session. We perform database operations and then commit the transaction. However, in the case of an exception, we roll back the transaction. Finally, we close the session. This method is part of the hibernate-core library in the org.hibernate.Session package.