Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Transactions and Locking

Transactions and Isolation Levels

Learn how Hibernate transactions map to JDBC and JTA, how to commit and roll back safely, and what the isolation levels allow - dirty, non-repeatable and phantom reads.

Every Hibernate write happens inside a transaction: a unit of work the database either applies completely or not at all. Hibernate does not invent transactions, it drives the ones your database and JDBC driver provide. This lesson shows the transaction API, what flush and commit really do, and how isolation levels decide what concurrent users can see.

Hibernate is not available in the browser, so its API code is read-only. The runnable programs use JDBC and H2, which Hibernate sits on, to show commit, rollback and isolation with real connections.

The transaction API

Java
try (Session session = sessionFactory.openSession()) {
    Transaction tx = session.beginTransaction();
    try {
        Account from = session.find(Account.class, 1L);
        Account to = session.find(Account.class, 2L);
        from.withdraw(100);
        to.deposit(100);
        tx.commit();                // flush + COMMIT
    } catch (RuntimeException e) {
        if (tx.getStatus().canRollback()) tx.rollback();
        throw e;
    }
}

Newer code uses sessionFactory.inTransaction(session -> { ... }), which opens the session, begins the transaction, commits when the lambda returns and rolls back if it throws:

Java
sessionFactory.inTransaction(session -> {
    session.persist(new Account("ada", 500));
});

With Spring you write @Transactional on a service method and the framework does the same through a proxy. Under the hood there is one Session per transaction, bound to the thread (or the reactive context). Hibernate supports two transaction coordinators: JDBC (plain Connection, used in most apps) and JTA (container-managed, for distributed transactions).

What commit does

commit() runs in order:

  1. flush(): Hibernate writes pending inserts, updates and deletes (see Flush and Dirty Checking).
  2. The JDBC commit.
  3. After-completion callbacks: second-level cache updates, @PostCommit-style listeners.

If anything throws, call rollback(). After an exception from Hibernate the session's state is unreliable, so discard the session; do not keep using it.

Rollback does not restore your Java objects. Entities you modified in memory keep their new values. Re-read them in a new session.

ACID in one table

Property Meaning
Atomicity all statements apply or none
Consistency constraints hold before and after
Isolation concurrent transactions do not see each other's half-done work
Durability committed data survives a crash

The first two are straightforward. Isolation is a spectrum, and that is the interesting part.

Java Commit and rollback with JDBC (the layer under Hibernate)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Isolation levels and anomalies

When two transactions run at the same time, three anomalies can occur:

  • Dirty read: you read data another transaction has not committed (and may roll back).
  • Non-repeatable read: you read a row twice and the second read sees a committed change.
  • Phantom read: you run the same range query twice and new rows appear.

The SQL standard defines four levels:

Level Dirty read Non-repeatable read Phantom read
READ_UNCOMMITTED possible possible possible
READ_COMMITTED prevented possible possible
REPEATABLE_READ prevented prevented possible (not in MySQL InnoDB or PostgreSQL)
SERIALIZABLE prevented prevented prevented

Most databases default to READ_COMMITTED (PostgreSQL, Oracle, SQL Server) or REPEATABLE_READ (MySQL InnoDB). Set the level for all connections in the pool, or per transaction with Spring's @Transactional(isolation = Isolation.SERIALIZABLE):

PROPERTIES
hibernate.connection.isolation=2   # 2 = READ_COMMITTED (java.sql.Connection constants)

Higher isolation means fewer anomalies and more locking or more failed transactions that must be retried. SERIALIZABLE in PostgreSQL does not block readers; it aborts a transaction with a serialization failure when it detects a conflict, and the application must retry (see Retries, Deadlocks and Concurrency Patterns).

Hibernate adds its own layer: the first-level cache gives you repeatable reads for entities by id inside one session regardless of the database level, because a second find returns the cached instance. That is not true for queries, which still hit the database.

Java Read committed: a second connection sees only committed data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Practical rules

  • Keep transactions short: no user interaction, no remote calls, no sleeping inside one.
  • One transaction per use case at the service layer, not one per DAO call.
  • Mark read-only work as read-only (@Transactional(readOnly = true) or session.setDefaultReadOnly(true)): Hibernate skips dirty checking and some drivers route to replicas.
  • Never catch a database exception inside the transaction and carry on: the transaction may be marked rollback-only (PostgreSQL aborts the whole transaction after one error).
  • Do not rely on SERIALIZABLE everywhere. Decide per use case, and prefer explicit locking (next lessons) for the few spots that need it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Transaction.commit() do first?

    commit triggers a flush, then the JDBC commit, then after-completion callbacks.
  2. 2. After a rollback, what is true for entities you modified in memory?

    Rollback undoes database changes only; Java objects are not reverted.
  3. 3. Which anomaly does READ_COMMITTED still allow?

    READ_COMMITTED stops dirty reads but a committed change by another transaction can appear between two reads.
  4. 4. Which habit keeps transactions healthy?

    Long transactions hold locks and connections; short ones scale.

Summary

  • Hibernate drives JDBC or JTA transactions; commit flushes, commits and runs callbacks.
  • Roll back on failure, discard the session and reload objects afterwards.
  • Isolation levels trade anomalies (dirty, non-repeatable, phantom reads) against locking and retries.
  • Keep transactions short, scoped to a use case, and read-only when possible.

Next: Optimistic Locking with @Version