Menu

Transactions in Hibernate

Transactions in Hibernate

Why Transactions Are Required

Every database operation that changes data must run inside a transaction. A transaction groups several operations so they either all succeed or all fail.

In a plain Java application, Hibernate uses resource-local JDBC transactions through the Transaction interface. In application servers, JTA can manage transactions. In Spring applications, the @Transactional annotation handles this, which is covered in Lesson 26.

Manual and Managed Transactions

Transaction tx = null;
try (Session session = sessionFactory.openSession()) {
    tx = session.beginTransaction();
    session.persist(new Student("Ravi"));
    tx.commit();
} catch (RuntimeException e) {
    if (tx != null) tx.rollback();
    throw e;
}

sessionFactory.inTransaction(session -> {
    session.persist(new Student("Meera"));
});

Code Explanation:

  • beginTransaction() starts a transaction on the session.
  • commit() flushes pending changes and makes them permanent.
  • If an exception occurs, rollback() undoes everything done in the transaction.
  • inTransaction() opens a session, begins a transaction, commits on success, rolls back on failure, and closes the session.
  • The second form is shorter and avoids forgotten rollbacks, so it is preferred for simple cases.

An exception thrown by a session usually leaves that session in an unreliable state. Discard it and don't reuse it.


Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details