Show List

Hibernate Session and Transaction API

Hibernate Session API is the central component of the Hibernate framework and is used to interact with the database. It provides several methods to fetch, persist, and delete data from the database.

A Hibernate session represents a unit of work with the database, and all the data changes made within a session are persisted to the database when the session is committed.

Here's an example of how to use the Hibernate Session API:

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

// Perform database operations here

transaction.commit();
session.close();

The SessionFactory is a singleton object that is used to create Session objects. The Session is created by calling the openSession method on the SessionFactory.

Next, a transaction is started by calling session.beginTransaction(). All the database operations are performed within the transaction. Finally, the transaction is committed by calling transaction.commit(), and the session is closed by calling session.close().

In this example, the HibernateUtil class contains the code to initialize the SessionFactory.

The Transaction API provides a mechanism to group multiple database operations into a single transaction. The transaction is either committed or rolled back as a whole. If any of the operations in the transaction fail, the entire transaction is rolled back, ensuring the database remains in a consistent state.

Here's an example of how to use the Hibernate Transaction API:

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction(); try { // Perform database operations here transaction.commit(); } catch (Exception ex) { transaction.rollback(); // Log the exception } finally { session.close(); }
In this example, the transaction is started by calling session.beginTransaction(). If any exception occurs during the database operations, the transaction is rolled back by calling transaction.rollback(). Finally, the session is closed by calling session.close().

    Leave a Comment


  • captcha text