Skip to lesson

Transient, managed, detached and removed

A service loads product 1 twice, then changes the price on one copy and the stock on the other. Which object is the truth? Hibernate needs one tracked object per row and a clear state for every object.

The persistence context: a first-level cache

A persistence context is the set of entity objects Hibernate is tracking right now: a map from entity type and id to the one Java object for that row. It is also called the first-level cache.

Product 1 is looked up twice inside one transaction. The first findById sends a SELECT and stores the object in the map; the second finds it there and sends no SQL.

Text
# persistence-lab: src/main/resources/application.properties (the parts that matter here)spring.datasource.url=${DB_URL}spring.datasource.username=${DB_USER}spring.datasource.password=${DB_PASSWORD}spring.jpa.hibernate.ddl-auto=validatespring.jpa.open-in-view=falsespring.main.web-application-type=none# short log lines: level, logger, messagelogging.pattern.console=%-5level %logger{36} : %msg%nlogging.level.root=WARNlogging.level.org.hibernate.SQL=DEBUG

Example 1 · One SELECT and one object inside a transaction

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

FirstLevelCacheDemo.javaJava
// src/main/java/com/shoplite/lab/FirstLevelCacheDemo.javapackage com.shoplite.lab;
import java.util.List;
import org.springframework.stereotype.Component;import org.springframework.transaction.support.TransactionTemplate;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("first-level-cache")public class FirstLevelCacheDemo implements LabDemo {
    private final ProductRepository products;    private final TransactionTemplate tx;
    public FirstLevelCacheDemo(ProductRepository products, TransactionTemplate tx) {        this.products = products;        this.tx = tx;    }
    @Override    public void run() {        System.out.println("-- One transaction, two lookups of product 1");        tx.executeWithoutResult(status -> {            Product a = products.findById(1).orElseThrow();            Product b = products.findById(1).orElseThrow();            System.out.println("a == b: " + (a == b));
            List<Product> list = products.findAllById(List.of(1, 2));            System.out.println("query result holds the same object: " + (list.get(0) == a));        });
        System.out.println("-- Two lookups, each in its own transaction");        Product c = products.findById(1).orElseThrow();        Product d = products.findById(1).orElseThrow();        System.out.println("c == d: " + (c == d));        System.out.println("c.equals(d): " + c.equals(d));    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=first-level-cache"
-- One transaction, two lookups of product 1
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
a == b: true
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id in (?,?)
query result holds the same object: true
-- Two lookups, each in its own transaction
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
c == d: false
c.equals(d): true

What this code does

  • Inside one transaction the second findById(1) sends no SQL: the persistence context already holds product 1, so a == b is true. findAllById is a query, so it does go to the database, but the row for id 1 comes back as the same object a.
  • Outside a transaction each repository call runs in its own short transaction with its own persistence context. So the two lookups send two SELECTs and give two different objects (c == d is false).
  • c.equals(d) is still true because ShopLite entities compare by id (the equals and hashCode lesson). == asks "same object?", equals asks "same row?".

The map only helps lookups by id (findById, em.find, getReferenceById). A query such as findAll() always goes to the database, but for each row it returns, Hibernate checks the map and hands back the object you already have, not a second copy.

Without the map, two lookups of product 1 would give two objects, and Hibernate could not tell which one holds the truth. With it, the same id always gives the same object.

All examples in this module run in persistence-lab: a Spring Boot 4.1 project with the ShopLite entities from the Relationships module, a fresh copy of the ShopLite database and one demo class per idea. You pick a demo with --demo=name. The settings above print every SQL statement on one short line.

The four entity states

An entity state says how an entity object relates to the persistence context: transient (new, no row), managed (tracked), detached (has a row, not tracked) or removed (tracked, its row is deleted at commit).

Every entity object is in one of four states, and the state decides what Hibernate does with your changes. The picture shows the states and the calls that move an object between them.

The four states of an entity. A transient object, made with new, has no row and is not tracked. persist() makes it managed, which means Hibernate tracks it and writes its changes at commit. Commit, clear() or detach() make a managed object detached: it still has a row but is no longer tracked.

Example 2 · One category through all four states

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

LifecycleDemo.javaJava
// src/main/java/com/shoplite/lab/LifecycleDemo.javapackage com.shoplite.lab;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.category.Category;
import jakarta.persistence.EntityManager;
@Component("lifecycle")public class LifecycleDemo implements LabDemo {
    private final EntityManager em;
    public LifecycleDemo(EntityManager em) {        this.em = em;    }
    @Override    @Transactional    public void run() {        Category books = em.find(Category.class, 5);
        Category guides = new Category("Exam Guides", books);        show("1. new", guides);
        em.persist(guides);        show("2. after persist", guides);
        em.detach(guides);        show("3. after detach", guides);
        Category again = em.find(Category.class, guides.getId());        show("4. found again", again);        System.out.println("   same Java object as before? " + (again == guides));
        em.remove(again);        show("5. after remove", again);        System.out.println("-- method ends, Spring commits");    }
    private void show(String step, Category category) {        System.out.println(step + ": id=" + category.getId() + ", managed=" + em.contains(category));    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=lifecycle"
DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
1. new: id=null, managed=false
DEBUG org.hibernate.SQL : insert into categories (name,parent_id) values (?,?)
2. after persist: id=8, managed=true
3. after detach: id=8, managed=false
DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
4. found again: id=8, managed=true
   same Java object as before? false
5. after remove: id=8, managed=false
-- method ends, Spring commits
DEBUG org.hibernate.SQL : delete from categories where category_id=?

What this code does

  • Step 1 is transient (no id, not managed). persist makes it managed and, because ids come from MySQL's AUTO_INCREMENT, Hibernate sends the INSERT at once to learn the id 8 (the Flush lesson explains this exception to the rule).
  • After detach the object still has id 8 but is no longer tracked. find cannot hand back a detached object, so it sends a SELECT and builds a new managed one: again == guides is false.
  • remove makes the object removed (managed=false), yet the DELETE appears only after "method ends": it is sent when Spring commits.

The calls that move an object between states: persist (transient to managed), find or a query (row to managed), detach, clear or the end of the transaction (managed to detached), merge (a detached object is copied into a managed one) and remove (managed to removed).

A common trap is to think every object with an id is "saved". An id only means the row exists; whether your next change reaches the database depends on whether the object is managed.

Order of execution

The life of one new product object

Tap the steps in the order they happen.

One persistence context per transaction in Spring

A shared EntityManager proxy is the EntityManager object Spring injects into a bean. It holds no state of its own: each call is forwarded to the EntityManager of the transaction running on the current thread.

In Spring Boot a persistence context lives exactly as long as one transaction. It opens when a @Transactional method starts and closes when the method commits or rolls back.

Example 3 · Each transaction gets its own persistence context

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

ContextPerTransactionDemo.javaJava
// src/main/java/com/shoplite/lab/ContextPerTransactionDemo.javapackage com.shoplite.lab;
import org.springframework.stereotype.Component;import org.springframework.transaction.support.TransactionTemplate;
import com.shoplite.product.Product;
import jakarta.persistence.EntityManager;
@Component("context-per-transaction")public class ContextPerTransactionDemo implements LabDemo {
    private final EntityManager em;          // a shared proxy: safe to inject into a singleton    private final TransactionTemplate tx;
    public ContextPerTransactionDemo(EntityManager em, TransactionTemplate tx) {        this.em = em;        this.tx = tx;    }
    @Override    public void run() {        Product loaded = tx.execute(status -> {            Product p = em.find(Product.class, 3);            Product q = em.find(Product.class, 3);            System.out.println("transaction 1: p == q? " + (p == q) + ", managed=" + em.contains(p));            return p;        });        System.out.println("transaction 1 committed; its persistence context is closed");
        tx.executeWithoutResult(status -> {            System.out.println("transaction 2: old object managed=" + em.contains(loaded));            Product fresh = em.find(Product.class, 3);            System.out.println("transaction 2: fresh == old? " + (fresh == loaded)                    + ", fresh managed=" + em.contains(fresh));        });    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=context-per-transaction"
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
transaction 1: p == q? true, managed=true
transaction 1 committed; its persistence context is closed
transaction 2: old object managed=false
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
transaction 2: fresh == old? false, fresh managed=true

What this code does

  • Transaction 1 finds product 3 twice with one SELECT and gets one object, which it returns. When the lambda ends, the transaction commits and its persistence context closes.
  • Transaction 2 has a new, empty persistence context. The old object is detached there (managed=false), and find sends a new SELECT and builds a fresh object.
  • The same injected em worked in both transactions: it is Spring's shared proxy, which always talks to the current transaction's EntityManager.

Constructor injection of EntityManager gives this proxy, so one injected instance is safe in a singleton service used by many requests at once. Older code writes @PersistenceContext private EntityManager em;, which gives the same proxy, and Spring Data repositories use it inside.

The Transactions module covers transaction boundaries in depth. The examples here use TransactionTemplate when a listing needs two transactions: tx.execute(status -> ...) runs the lambda in one transaction, like a @Transactional method.

ShopLite sets spring.jpa.open-in-view=false, so the persistence context really does close when the service method returns. The lesson on LazyInitializationException shows what that means for controllers.

Checking the state with em.contains()

em.contains(entity) returns true only when that exact object is managed by the current persistence context. It is false for transient, detached and removed objects, and it never sends SQL.

The next listing asks em.contains() about one object before and after clear(), then calls persist on a detached object.

Example 4 · em.contains(), clear() and persist on a detached object

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

ContainsDemo.javaJava
// src/main/java/com/shoplite/lab/ContainsDemo.javapackage com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.category.Category;import com.shoplite.product.Product;
import jakarta.persistence.EntityManager;
@Component("contains")public class ContainsDemo implements LabDemo {
    private final EntityManager em;
    public ContainsDemo(EntityManager em) {        this.em = em;    }
    @Override    @Transactional    public void run() {        Category books = em.getReference(Category.class, 5);        Product draft = new Product("BK-GATE26", "GATE CSE Guide 2026", books, new BigDecimal("749.00"), 20);        System.out.println("new object:      contains=" + em.contains(draft));
        Product kurta = em.find(Product.class, 12);        System.out.println("after find:      contains=" + em.contains(kurta));
        em.clear();        System.out.println("after clear:     contains=" + em.contains(kurta));
        try {            em.persist(kurta);        } catch (RuntimeException e) {            System.out.println("persist(detached) -> " + e.getClass().getName());            System.out.println("  " + e.getMessage());        }    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=contains"
new object:      contains=false
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
after find:      contains=true
after clear:     contains=false
persist(detached) -> jakarta.persistence.EntityExistsException
  Detached entity passed to persist: com.shoplite.product.Product
ERROR o.s.boot.SpringApplication : Application run failed
org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
	... (stack trace trimmed)

What this code does

  • A new object is not managed, a found one is, and em.clear() detaches everything in the persistence context at once, so kurta turns false.
  • persist(kurta) fails with EntityExistsException: Detached entity passed to persist. persist means "insert this new object", and Hibernate refuses an object that already has a row.
  • The demo catches the exception, but the transaction is already marked rollback-only, so Spring's commit throws UnexpectedRollbackException. Never catch a persistence exception and carry on in the same transaction.

Use em.contains() while learning, in tests and when debugging "why was my change not saved?". Business code should not need it: a well-shaped service loads what it changes inside one transaction, so the objects are always managed.

persist is only for new objects: passing it a detached object (one with an id) throws EntityExistsException: Detached entity passed to persist. Any exception from the EntityManager marks the whole transaction for rollback; catching it does not undo that, and the commit then fails with UnexpectedRollbackException.

Predict the output

Is the object managed?

Each method runs inside a @Transactional service. Pick what it returns.

Round 1 of 4

A product loaded by id.

Product p = products.findById(1).orElseThrow();
return em.contains(p);

Next step

Check your understanding

12 quick questions