Java and Spring Level 2 This level · 11 of 84
Medium java hibernate

Which operations move an entity between these four states?

The 30 second answer

An entity created with new becomes managed through persist or save. Changes to a managed entity are saved automatically at flush. Closing the context, clear, and evict or detach make it detached, and serialization produces a detached copy. merge copies a detached entity's data onto a new managed instance and returns it. remove makes it removed, and the DELETE runs at flush.

Could you say this in an interview?

From transient to managed: persist and save. Per the docs, an entity created with new is in the new state. You make it persistent by associating it with a Session or EntityManager, that is, with persist. The Session's persist follows the exact semantics of the Jakarta Persistence specification, and Hibernate's EntityManager implementation delegates to it. If the id is generated, it is assigned automatically when save or persist is called. Otherwise you must assign it manually before that.

Inside the managed state: dirty checking and flush. Any change to a managed entity is detected automatically and persisted when the persistence context is flushed. There is no need to call a particular method to make your modifications persistent. Flushing is the process of synchronizing the state of the persistence context with the database. The persistence context acts as a transactional write-behind cache: changes are first applied in memory and turned into INSERT, UPDATE or DELETE statements at flush time. In the default AUTO flush mode, Hibernate flushes in three situations:

  • before a transaction commits
  • before a JPQL or HQL query that overlaps with the queued entity actions
  • before a native SQL query that has no registered synchronization

From managed to detached: close, clear, evict or detach, and serialization. The docs name four ways. Once the persistence context is closed, all data associated with it becomes detached. clear() has the same effect. evict() in Hibernate or detach() in JPA detaches a single entity. Serialization makes the deserialized copy detached, while the original instance stays managed. You can check whether an entity is still attached with contains(entity).

From detached back to managed: merge. A detached entity can still be modified, but the context no longer knows about those changes, and the application has to make them persistent again. merge copies the detached entity's data onto a new managed instance and returns it. So you must use the returned value: person = entityManager.merge(person);.

From managed to removed: remove. Calling remove makes the entity removed. The EntityManager only accepts a managed entity for remove, while Hibernate's own Session delete also accepts a detached one.

Rollback. Per the docs, if the EntityManager or Session throws an exception, you must immediately roll back the transaction and close the EntityManager or Session. Rolling back does not put your business objects back into the state they were in at the start of the transaction. After that, the database state and your objects are out of sync, and you have to start over.

Code: each transition in a Spring Boot service.

Transient to managed. Spring Data's save calls entityManager.persist when the entity is new, and merge otherwise.

// (1) transient -> managed
@Transactional
public Order create(String customer) {
    Order order = new Order(customer);          // transient: no id, no context
    order.addItem(new OrderItem("SKU-1"));
    Order saved = orders.save(order);           // new entity, so save() calls em.persist(): managed
    System.out.println(em.contains(saved));     // true
    return saved;                               // INSERTs run at flush, before commit
}

Dirty checking. The entity is managed, so changing a field is enough; there is no save call.

// (2) dirty checking: no save() call
@Transactional
public void markPaid(Long id) {
    Order order = orders.findById(id).orElseThrow(); // managed
    order.setStatus("PAID");                         // UPDATE runs at flush, before commit
}

Detached to managed with merge. The argument stays detached; only the returned instance is managed.

// (4) detached -> managed with merge
@Transactional
public Order rename(Order detached, String newStatus) {
    detached.setStatus(newStatus);          // not tracked: detached
    Order managed = em.merge(detached);     // copies state onto a managed instance
    System.out.println(managed == detached);       // false
    System.out.println(em.contains(detached));     // false
    return managed;                         // always use the returned value
}

Managed to removed, and back to managed before flush. Per the Jakarta Persistence spec, calling persist on a removed entity makes it managed again.

// (5) managed -> removed, and back to managed before flush
@Transactional
public void removeThenRestore(Long id) {
    Order order = em.find(Order.class, id);  // managed
    em.remove(order);                        // removed: DELETE is only scheduled
    System.out.println(em.contains(order));  // false: removed entities are not "contained"
    em.persist(order);                       // removed -> managed again, before any flush
    System.out.println(em.contains(order));  // true; no DELETE is sent at commit
}
Sources (7)
  1. Hibernate ORM User Guide: Making entities persistentdocs.jboss.org
  2. Hibernate ORM User Guide: Modifying managed/persistent statedocs.jboss.org
  3. Spring Data JPA Reference: Persisting Entities (save calls persist or merge)docs.spring.io
  4. Jakarta Persistence 3.1 specification: Persisting an Entity Instance (persist on a removed entity)jakarta.ee
  5. Hibernate ORM User Guide: Working with detached data and mergedocs.jboss.org
  6. Hibernate ORM User Guide: Flushingdocs.jboss.org
  7. Hibernate ORM User Guide: Exception handlingdocs.jboss.org
Previous
Next