Hibernate Persistence

Hibernate Transaction Management

Learn how to define a unit of work, commit successful changes, roll back failures, and close Hibernate resources safely.

What Is a Transaction?

A transaction groups related database operations into one unit of work. If an operation fails, the application can roll back the complete unit instead of leaving partial changes in the database.

Atomicity

All operations succeed together or none are applied.

Consistency

Committed work preserves database rules and constraints.

Isolation

Concurrent transactions do not see invalid intermediate state.

Durability

Committed data survives a later failure.

Hibernate Transaction API

A Hibernate Transaction represents the transaction boundary for a unit of work. It is obtained from a session:

try (Session session = sessionFactory.openSession()) {
    Transaction transaction = session.beginTransaction();
    // Database work belongs inside this unit of work.
    transaction.commit();
}
OperationPurpose
session.beginTransaction()Starts a transaction and returns its Hibernate transaction handle.
transaction.commit()Flushes pending changes and commits the unit of work.
transaction.rollback()Discards the transaction's uncommitted database changes.
transaction.setTimeout(seconds)Sets a timeout where supported by the transaction integration.
transaction.isActive()Checks whether the transaction is currently active.
Version note: older tutorials may mention methods such as begin(), wasCommited(), wasRolledBack(), or synchronization registration. Check the Hibernate version's API before using them; current application code normally uses beginTransaction(), commit(), rollback(), and isActive().

Recommended Commit and Rollback Pattern

Start the transaction before persistence work, commit only after every operation succeeds, and roll back in the failure path.

try (Session session = sessionFactory.openSession()) {
    Transaction transaction = session.beginTransaction();
    try {
        session.persist(employee);
        session.persist(address);
        transaction.commit();
    } catch (RuntimeException exception) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw exception;
    }
}

Do not continue using a session after a transaction failure without deciding whether it can safely be reused. Closing the session and starting a new unit of work is often the safest recovery strategy.

Complete Hibernate Example

public void saveEmployee(Employee employee) {
    try (SessionFactory factory = new Configuration()
            .configure()
            .buildSessionFactory();
         Session session = factory.openSession()) {

        Transaction transaction = session.beginTransaction();
        try {
            session.persist(employee);
            transaction.commit();
        } catch (RuntimeException exception) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw exception;
        }
    }
}

In a long-running application, create the SessionFactory once and reuse it. The example closes it for clarity; application shutdown code should own factory cleanup.

Flush, Commit, and Rollback

  • Persist: makes a new entity managed in the current persistence context.
  • Flush: synchronizes pending changes with SQL statements. Hibernate commonly flushes before commit.
  • Commit: makes the transaction's database changes durable.
  • Rollback: reverses uncommitted database changes; it does not undo external side effects such as an email already sent.
Important: a successful Java method does not guarantee that the database commit succeeded. Treat commit as the point at which the unit of work completes successfully.

JDBC and JTA Transactions

Hibernate can integrate with different transaction environments:

Resource-local / JDBC

The application begins and commits a transaction through the Hibernate session. This is common for a standalone application using one database connection.

JTA

A container or transaction manager coordinates one or more resources. Hibernate participates in the surrounding transaction rather than independently controlling every resource.

In Spring applications, use Spring's @Transactional boundary rather than manually opening and committing a Hibernate transaction in every service method.

Timeouts and Isolation

Transaction timeout and isolation behavior depend on the JDBC driver, database, connection pool, and transaction integration. Configure them at the layer responsible for the transaction environment and test them against the real database.

Transaction transaction = session.beginTransaction();
transaction.setTimeout(30);
try {
    // Work should finish within the configured limit.
    transaction.commit();
} catch (RuntimeException exception) {
    if (transaction.isActive()) transaction.rollback();
    throw exception;
}

Common Transaction Mistakes

  • Opening a session without beginning a transaction for a write operation.
  • Forgetting to roll back after an exception.
  • Calling rollback after the transaction has already completed without checking its state.
  • Keeping a transaction open while waiting for network calls or user input.
  • Sharing a session or transaction across threads.
  • Creating a new SessionFactory for every request.
  • Assuming rollback can undo messages or other external side effects.
  • Using automatic schema updates as a substitute for database migrations.

Transaction Best Practices

  1. Keep one transaction focused on one business unit of work.
  2. Keep sessions and transactions short-lived.
  3. Commit only after all required persistence operations succeed.
  4. Roll back in the catch path and rethrow the original exception.
  5. Close sessions with try-with-resources.
  6. Let Spring or JTA manage boundaries when the application uses a transaction manager.
  7. Design retries carefully so repeated work is safe and idempotent.
Summary: begin a transaction, perform the complete unit of work, commit on success, roll back on failure, and always release the session and connection resources.