MODULE 3 · TOPIC 6 · VISUAL JPA & HIBERNATE LAB

Transaction Management

A transaction groups database operations into a unit of work. JPA EntityTransaction controls resource-local transactions; Hibernate flushes managed state and JDBC/database transactions enforce durability and isolation. This topic distinguishes atomic rollback, isolation phenomena, optimistic version checks, pessimistic locks and transaction boundaries. In container-managed applications JTA or framework transaction management may provide the boundary instead.

Browser-based JPA and Hibernate simulations. Change inputs and trace entity state, SQL, database rows and transactions. No real Java or database operations are executed.

1. Atomicity — money transfer with failure injection

Atomicity means related writes either all commit or all roll back. A transfer must debit one row and credit another within one boundary. This sequential teaching example omits concurrent balance locking; production transfers also need suitable concurrency control and validation.

Why this example? Choose a transfer amount and inject a credit failure to see whether either balance changes permanently.

Java / JPA code
SQL / simulation outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Why this step happens
See all steps in this scenario

    Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

    What this animation explains

    One transaction protects the invariant that the combined balance remains constant.

    Try and observe

    Try 200 with failure and 1200 with no failure; both must leave the original balances.

    2. Transaction boundaries — partial commits

    Atomicity only covers operations in the same database transaction. If the debit commits independently, a later failure cannot be rolled back by the second transaction. A compensation workflow is different from database rollback and needs explicit design.

    Why this example? Compare one boundary with two independent boundaries and inject failure in the second operation.

    Java / JPA code
    SQL / simulation outputConsole
    Data operationsCompact blocks
    CurrentResultError / rejected
    Why this step happens
    See all steps in this scenario

      Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

      What this animation explains

      Incorrect transaction boundaries can violate a business invariant even if each transaction is individually valid.

      Try and observe

      Use two transactions and fail credit; total becomes 1300 in this unsafe example.

      3. Isolation — dirty reads under concurrent transactions

      Isolation defines which effects of other transactions a transaction can observe. A dirty read observes uncommitted work that may later roll back. READ COMMITTED excludes dirty reads; READ UNCOMMITTED may allow them, though actual database implementations differ.

      Why this example? Choose an isolation level and writer outcome; observe the reader value before commit.

      Java / JPA code
      SQL / simulation outputConsole
      Data operationsCompact blocks
      CurrentResultError / rejected
      Why this step happens
      See all steps in this scenario

        Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

        What this animation explains

        A reader can see a value that never becomes committed under an isolation level allowing dirty reads.

        Try and observe

        Choose READ UNCOMMITTED and writer rollback, then READ COMMITTED.

        4. Isolation — nonrepeatable reads and snapshots

        A nonrepeatable read occurs when a row read twice in one transaction changes between reads due to another committed transaction. READ COMMITTED can allow this. A repeatable-read snapshot preserves the earlier view in this simplified model; database-specific locks or conflicts may change the interleaving.

        Why this example? Change isolation and whether another transaction commits an update. Compare the two SQL reads.

        Java / JPA code
        SQL / simulation outputConsole
        Data operationsCompact blocks
        CurrentResultError / rejected
        Why this step happens
        See all steps in this scenario

          Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

          What this animation explains

          Persistence-context caching can mask database isolation effects; this example models actual repeated SQL reads.

          Try and observe

          Observe 80 then 95 under READ COMMITTED, then choose the snapshot.

          5. Optimistic locking — version conflict and lost update

          @Version identifies a version attribute that Hibernate checks when updating a managed row. If another transaction has already changed the version, the stale write is rejected. Without version checking, last-writer-wins can lose earlier changes under this controlled interleaving.

          Why this example? Choose version mapping and commit order; compare SQL predicates, conflict and final marks.

          Java / JPA code
          SQL / simulation outputConsole
          Data operationsCompact blocks
          CurrentResultError / rejected
          Why this step happens
          See all steps in this scenario

            Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

            What this animation explains

            Optimistic locking detects conflicts rather than holding a lock across user think time.

            Try and observe

            Reverse commit order with version enabled, then disable version checking.

            6. Pessimistic locking — waiting and timeout

            Pessimistic locking requests database locks while a transaction is active. A conflicting update can wait until the lock holder completes or a timeout occurs. Locks have a cost: contention, timeout and deadlock risk. Normal reads may not request explicit locks, but writes still acquire database locks.

            Why this example? Select lock mode and the timing of the second writer relative to lock release.

            Java / JPA code
            SQL / simulation outputConsole
            Data operationsCompact blocks
            CurrentResultError / rejected
            Why this step happens
            See all steps in this scenario

              Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.

              What this animation explains

              Locking controls when competing transactions can proceed; it is not the same as optimistic version checking.

              Try and observe

              Choose pessimistic write with a timeout, then release before timeout.

              API and configuration reference

              Refer to these APIs and settings while building the real JPA project. Use a transaction for write operations.

              API / settingWhy and when to use it
              tx.begin()Start resource-local transaction
              tx.commit()Synchronize and commit successful work
              tx.rollback()Reverse uncommitted database work
              tx.isActive()Check before rollback
              @VersionDetect conflicting updates with version checking
              LockModeType.PESSIMISTIC_WRITERequest a database lock within a transaction

              Worked practical examples

              Follow these procedures with the Jakarta Persistence 3.1 / Hibernate ORM 6.6 teaching project. Snippets require the indicated entities and an open EntityManager; SQL varies by dialect.

              1. Atomic account transfer with failure handling

              Procedure

              1. Create Account entity with assigned Long id and long balance (integer units for this lab). Register it and seed balances 1000 and 500.
              2. Begin one transaction, load both rows, validate the amount, then change both balances.
              3. Force a failure before credit to test rollback. Use a fresh context to verify committed values.
              Code / configuration
              var tx=em.getTransaction();
              try {
                tx.begin();
                Account a=em.find(Account.class,1L);
                Account b=em.find(Account.class,2L);
                long amount=200;
                if(a.balance<amount) throw new IllegalStateException("Insufficient funds");
                a.balance-=amount;
                // optionally throw new IllegalStateException("Simulated failure");
                b.balance+=amount;
                tx.commit();
              } catch(RuntimeException ex) {
                if(tx.isActive()) tx.rollback();
                throw ex;
              }
              Expected result: Success: 800 and 700. A failure before commit: both original committed balances remain.

              2. Optimistic locking with two persistence contexts

              Procedure

              1. Add @Version long version to Student in the disposable lab and seed one row.
              2. Open two EntityManagers and begin transactions; both load the same row.
              3. Commit context A, then attempt to commit conflicting changes in B. Catch OptimisticLockException or a wrapped RollbackException and roll back if active.
              4. Reload with a new context before retrying the business operation.
              Code / configuration
              // In Student entity:
              @Version public long version;
              // In two distinct active contexts a and b:
              Student s1=a.find(Student.class,101L);
              Student s2=b.find(Student.class,101L);
              s1.marks=90;
              s2.marks=95;
              a.getTransaction().commit();
              b.getTransaction().commit(); // conflict expected if both loaded old version
              Expected result: The second conflicting update is rejected under the modeled conditions; final committed marks remain 90.

              Predict the outcome before you run

              Try answering these questions, then expand each answer and repeat the appropriate simulation.

              1. Why is one transaction needed for both sides of a transfer?

              Atomicity prevents a partial debit without the corresponding credit.

              2. Does rollback reset Java object fields?

              No. Verify database state in a fresh context.

              3. Should a long-running web request hold a pessimistic lock?

              Keep lock duration short and avoid waiting for user input inside a transaction.

              Hands-on practice and assessment

              Programming challenge

              Use the H2 lab to run a two-account transfer, intentionally fail the second operation, roll back, and verify committed balances in a fresh context. Add @Version to a test entity and compare concurrent updates from separate contexts.

              Edit this practice scratchpad and copy it into your real Java project. The browser does not compile arbitrary Java.

              Quick assessment

              Key points and real Hibernate notes

              Use short transactions, handle exceptions and roll back active transactions before discarding the context. Isolation and lock behavior depend on database and configuration. These browser labs model controlled interleavings; they are not concurrency benchmarks.