Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 119 ยท JPA and Hibernate

Entity Lifecycle and Transactions

Understand JPA entity states, persist vs merge, dirty checking and flush, how @Transactional commits and rolls back, and optimistic locking with @Version.

With plain JDBC, nothing reaches the database unless you run an INSERT, UPDATE or DELETE. JPA works differently. You change a field on an entity, never call any "save" method, and at commit Hibernate writes an UPDATE anyway. Or you do call merge(), keep editing the same object, and those edits are silently lost. Both behaviors follow from one idea: the persistence context tracks a set of managed entities and writes their changes when it flushes.

This lesson explains the four states an entity can be in, what persist, merge, remove and flush actually do, how Spring's @Transactional decides between commit and rollback, and how @Version stops two users from overwriting each other's work. Because JPA can't run in our sandbox, the examples use small, faithful re-implementations of each mechanism over a real H2 database. They print the SQL Hibernate would send, so you can predict it in your own code. You should know Transactions with JDBC; everything here is built on it.

The four entity states

State Meaning Changes written to the database?
Transient (new) A plain object created with new; the persistence context doesn't know it. No
Managed Known to the current persistence context, which tracks its changes. Yes, at flush
Detached Was managed, but its persistence context was closed or cleared, or it was explicitly detached. It usually has an id. No
Removed Managed, but scheduled for deletion. DELETE at flush

The transitions are just as important:

TEXT
              persist()                     remove()
 TRANSIENT โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ MANAGED โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ REMOVED
                           โ–ฒ   โ”‚                            โ”‚ flush/commit
           find(), query,  โ”‚   โ”‚ close(), clear(),          โ–ผ
           merge() returns โ”‚   โ”‚ detach(), commit*      (row deleted)
                           โ”‚   โ–ผ
                         DETACHED

* In Spring, the persistence context normally ends together with the transaction, so after a @Transactional method returns, the entities it loaded are detached.

persist, find, remove and dirty checking

persist(entity) makes a new object managed. It does not necessarily run an INSERT right away: Hibernate queues the insert and runs it at flush. (The exception is GenerationType.IDENTITY: the id comes from the insert itself, so Hibernate must insert immediately, which also disables JDBC insert batching. Sequences don't have this problem.)

find(Product.class, id) returns a managed entity, from the persistence context if it is already there, or with a SELECT. At that moment Hibernate also stores a snapshot of the loaded values.

At flush, Hibernate compares every managed entity with its snapshot. Changed entities get an UPDATE; unchanged ones get nothing. This is dirty checking, and it is why JPA code that modifies data often has no save() call:

Java
@Transactional
public void reprice(long productId, int newPrice) {
    Product product = entityManager.find(Product.class, productId);
    product.setPrice(newPrice);          // that's it: the UPDATE happens at commit
}

remove(entity) marks a managed entity as removed, and the DELETE runs at flush. Calling it on a detached entity throws IllegalArgumentException; load the entity first (or use getReference(), which returns a lazy proxy without querying).

The mini entity manager below implements exactly these rules. Read the flush() method; it is the heart of JPA.

Java States, write-behind and dirty checking

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.

Four details to notice in the output:

  • The lamp got its id from the sequence at persist(), but the INSERT only ran at the first flush, and it already contained the price set after persist().
  • The chair's price changed and changed back, so the second flush wrote nothing for it. Dirty checking compares values, not "was a setter called".
  • The removed chair was deleted at flush, not at remove().
  • After clear(), the lamp is detached. Changing it does nothing.

By default Hibernate's UPDATE sets all columns of the entity, not just the changed ones (so the same prepared statement can be reused). @DynamicUpdate on the entity switches to changed columns only, which helps with very wide tables.

Flush is not commit

Flushing sends the pending SQL to the database; committing makes it permanent. A flushed change is still inside the open transaction and disappears on rollback. Hibernate flushes:

  • before the transaction commits,
  • before running a JPQL or native query whose result might depend on pending changes (FlushModeType.AUTO, the default), so your queries see your own changes,
  • whenever you call entityManager.flush() yourself.

An explicit flush() is useful when you want a constraint violation now, inside a try block, rather than at commit time far away from the code that caused it. You rarely need it otherwise.

Detached entities and merge

Detached entities appear everywhere in real applications: an entity loaded in one request and sent to a form, an object deserialized from JSON, an entity kept after its transaction ended. To write their changes, you need merge():

Java
Product edited = ...;                           // detached: from a form or another transaction
Product managed = entityManager.merge(edited);  // copies edited's state onto a managed instance

merge copies the state of its argument onto a managed instance (loading it with a SELECT if necessary) and returns that managed instance. The argument itself stays detached. This is the source of a classic bug: keep using the argument after merge() and your later changes are ignored.

Java merge copies state and returns a different object

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.

The new name never reached the database, because it was set on the detached object after the merge. The rule is short: use the return value of merge(), as in product = entityManager.merge(product);. Also note that persist() refuses an object that already has an id and isn't managed; Hibernate reports this as "detached entity passed to persist".

Spring Data's repository.save(entity) hides this choice: it calls persist for new entities and merge for the rest, and it returns the managed instance. That is why entity = repository.save(entity) is the correct way to call it.

Merging whole objects from a form or JSON is risky: any field the client didn't send (or sent on purpose) overwrites the database. In service code, prefer load, then change: find() the managed entity and copy only the fields this use case may change from a DTO. Dirty checking does the rest.

Transactions in JPA and Spring

JPA changes must happen inside a transaction. In plain Jakarta Persistence (with RESOURCE_LOCAL transactions) you manage it yourself, with the same shape as in JDBC:

Java
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
try {
    tx.begin();
    Product product = em.find(Product.class, 1L);
    product.setPrice(99);
    tx.commit();                         // flush + commit
} catch (RuntimeException e) {
    if (tx.isActive()) {
        tx.rollback();
    }
    throw e;
} finally {
    em.close();                          // everything it loaded is now detached
}

Jakarta Persistence 3.2 adds emf.runInTransaction(em -> ...) and callInTransaction(...) helpers for exactly this pattern. In a Spring application you write none of it. You annotate a service method:

Java
@Service
public class CatalogService {

    private final ProductRepository products;

    public CatalogService(ProductRepository products) {
        this.products = products;
    }

    @Transactional
    public void reprice(long id, int newPrice) {
        Product product = products.findById(id).orElseThrow();
        product.setPrice(newPrice);
    }

    @Transactional(readOnly = true)
    public List<ProductSummary> listCheap(int maxPrice) {
        return products.findSummariesByPriceLessThan(maxPrice);
    }
}

Spring wraps the bean in a proxy that begins a transaction before the method, binds one persistence context (and one JDBC connection) to it, and commits or rolls back afterwards. Aspect-Oriented Programming shows how that proxy works. readOnly = true tells Hibernate to skip dirty checking and snapshots, and lets some drivers route to a read replica.

Propagation

When a @Transactional method calls another one, propagation decides whether they share a transaction:

Propagation Behavior
REQUIRED (default) Join the current transaction, or start one if there is none.
REQUIRES_NEW Suspend the current transaction and run in a new, independent one (for example an audit log entry that must survive a rollback).
MANDATORY Join the current transaction; throw if there is none.
SUPPORTS / NOT_SUPPORTED / NEVER Run with, without or forbidding a transaction.
NESTED Run inside a savepoint of the current transaction (JDBC only).

With REQUIRED, an exception in an inner method marks the whole transaction rollback-only, even if the outer method catches it. The outer commit then fails with UnexpectedRollbackException.

Rollback rules: the checked exception trap

By default, Spring rolls back on unchecked exceptions (RuntimeException and Error) and commits on checked exceptions. This mirrors old EJB conventions, where checked exceptions were "business outcomes". It surprises nearly everyone who throws a checked exception from a service:

Java
@Transactional(rollbackFor = PaymentDeclinedException.class)
public void placeOrder(Order order) throws PaymentDeclinedException { ... }

The simulation below applies Spring's rules to three methods that insert an order and then fail.

Java When Transactional commits and when it rolls back

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.

The lantern order was committed even though the method failed. If an exception means "this business operation did not happen", either make it unchecked or list it in rollbackFor. Many teams set rollbackFor = Exception.class on every service, or simply use unchecked exceptions throughout.

Other @Transactional pitfalls

  • Self-invocation is not intercepted. If placeOrder() calls this.reserveStock() in the same class, the annotation on reserveStock() is ignored, because the call doesn't go through the proxy.
  • Catching the exception inside the method means the interceptor never sees it, so it commits. Rethrow, or call TransactionAspectSupport.currentTransactionStatus().setRollbackOnly().
  • After a rollback, don't reuse the entities. The persistence context is cleared and its objects may hold values that were never saved, including generated ids.
  • Keep transactions short. No HTTP calls, emails or user interaction inside them; locks and connections are held until the end.

Optimistic locking with @Version

Two users open the same product, both edit it, both save. With plain dirty checking, the second UPDATE silently overwrites the first: a lost update. JPA's answer is a version attribute:

Java
@Entity
public class Product {
    @Id
    private Long id;
    private String name;
    private int price;

    @Version
    private long version;
}

Hibernate now adds the version to every update, update product set name=?, price=?, version=? where id=? and version=?, with the new version (old + 1) in the SET and the version it loaded in the WHERE. If zero rows change, somebody else committed first, and Hibernate throws OptimisticLockException (Spring translates it to ObjectOptimisticLockingFailureException). No database locks are held while the user thinks, which is why this is called optimistic.

What you do next is a business decision: show the user the conflict, or for automatic operations, reload and retry.

Java Version checks and a retry loop

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.

Without the version check, Ben's save would have set the stock to 8 and erased Ana's sale. With it, Ben's first attempt fails, and the retry starts from the current state (7 in stock, version 1) and correctly saves 5. In Spring, retries are often added with Spring Retry's @Retryable or, since Spring Framework 7, the built-in @Retryable in the core resilience support. Make sure the retry wraps the whole transaction, not a method inside it.

Pessimistic locking

When conflicts are frequent and retries are expensive, lock the row instead:

Java
Product product = entityManager.find(Product.class, 1L, LockModeType.PESSIMISTIC_WRITE);

Hibernate issues select ... for update, and other transactions that want the same row wait until you commit. Use it for short, hot operations such as decrementing stock or allocating seat numbers, always with a lock timeout (jakarta.persistence.lock.timeout), and never across user think time.

Lifecycle callbacks

Entities can react to their own lifecycle with annotated methods: @PrePersist, @PostPersist, @PreUpdate, @PostUpdate, @PreRemove, @PostRemove and @PostLoad.

Java
@PrePersist
void onCreate() {
    createdAt = Instant.now();
}

@PreUpdate
void onUpdate() {
    updatedAt = Instant.now();
}

They suit small, entity-local work like timestamps or normalizing a field. Keep them free of queries and other entity managers, and remember that bulk JPQL updates skip them. Spring Data's auditing (@CreatedDate, @LastModifiedBy) builds on the same hooks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside a transaction you load a product with find(), call setPrice(50) and never call any save method. What happens at commit?

    The product is managed. At flush, Hibernate compares it with its snapshot and writes an UPDATE for the change.
  2. 2. Product result = em.merge(detached); Then you call detached.setName("New") and commit. Is the new name saved?

    merge copies the state onto a managed instance and returns it. Later changes to the argument are not tracked.
  3. 3. A Spring @Transactional method inserts a row and then throws a checked exception that is not listed in rollbackFor. What happens to the row?

    By default Spring rolls back only on RuntimeException and Error. Checked exceptions commit unless rollbackFor says otherwise.
  4. 4. What does entityManager.flush() do?

    Flush writes the pending changes, but they are still part of the open transaction and are undone on rollback.
  5. 5. With @Version, two transactions load version 3 of the same row and both update it. What happens to the second one?

    The first commit changed the version to 4, so the second update's WHERE version = 3 finds nothing. The application must reload and retry or report the conflict.

Summary

  • Entities are transient, managed, detached or removed. Only managed entities are tracked.
  • persist() makes a new entity managed; inserts usually wait for the flush (except with IDENTITY ids).
  • Dirty checking compares managed entities with their snapshots at flush and writes UPDATEs, with no save call needed.
  • Flush sends SQL; commit makes it permanent. Hibernate flushes before commit and before affected queries.
  • merge() copies a detached entity's state onto a managed one and returns it; always use the return value.
  • Spring's @Transactional commits on success, rolls back on unchecked exceptions, and commits on checked exceptions unless rollbackFor says otherwise. Self-invoked methods are not transactional.
  • @Version gives optimistic locking: conflicting updates fail with OptimisticLockException, and you reload and retry. PESSIMISTIC_WRITE locks rows with select ... for update.

Next: Hibernate's Native API: Session, HQL and Native SQL.