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

In Spring Boot, what state is an entity in after a @Transactional method commits?

The 30 second answer

Inside a @Transactional method, the persistence context is bound to the transaction and the entity is managed, so dirty checking works and changes are saved automatically at commit. Once the transaction ends and the context closes, the entity is detached. The exception is open session in view, which is on by default in web apps and keeps the context open until the request ends. That's why I map to DTOs inside the transaction.

Could you say this in an interview?

In a typical Spring Boot setup you don't open or close sessions yourself. Spring does it and binds the persistence context to the transaction of the @Transactional method.

Inside the transaction, the entity is managed. You create the entity with new, set its fields and call save or persist. From that moment it is managed. If you load an entity inside the same transaction and change a field, an UPDATE runs at the flush before commit, even without calling save. That is the dirty checking the Hibernate docs describe.

After commit, the entity is detached. When the transaction ends and the persistence context closes, per the Hibernate docs all its data becomes detached. The entity you return from the method still has its data, but nothing tracks its changes anymore.

The exception: open session in view. Per the Spring Boot docs, in a web application Spring Boot by default registers OpenEntityManagerInViewInterceptor to apply the Open EntityManager in View pattern, so lazy loading works in web views. The context then stays open until the end of the HTTP request. If you don't want this behavior, set spring.jpa.open-in-view to false in application.properties. With that setting, the entity is detached right after commit.

LazyInitializationException. The Hibernate docs say LAZY associations must be initialized before they are accessed, otherwise a LazyInitializationException is thrown. The best way to deal with it is to fetch all the required associations before the persistence context closes. This is where the detached state shows up in practice: touching an unloaded collection outside the transaction.

What I do in practice. I fetch the data I need inside the transaction and map it to DTOs right there. That way the controller never touches a detached entity, and I don't depend on lazy loading outside the transaction.

Interview line: "In Spring I don't manage the session lifecycle by hand, but I know where the boundary is. Entities are managed inside the transaction and detached after it, unless open session in view is on. That's why I map to DTOs inside the transaction and don't rely on lazy loading outside it."

Code: detached after commit, and the LazyInitializationException. This assumes spring.jpa.open-in-view=false. With the default open session in view, the same code works inside a web request, because the context stays open until the request ends.

// (3) returns an entity that is detached after commit (with open-in-view=false)
@Transactional
public Order load(Long id) {
    return orders.findById(id).orElseThrow();
}
import org.hibernate.LazyInitializationException;

public class OrderController {

    private final OrderService service;

    public OrderController(OrderService service) { this.service = service; }

    public void show(Long id) {
        Order order = service.load(id);           // transaction committed: order is detached
        System.out.println(order.getStatus());    // fine: basic fields were loaded
        try {
            order.getItems().size();              // lazy collection was never initialized
        } catch (LazyInitializationException e) {
            System.out.println("LazyInitializationException: " + e.getMessage());
        }
        OrderSummary dto = service.summary(id);   // fix: DTO built inside the transaction
        System.out.println(dto.skus());
    }
}

Code: the fix, a DTO built inside the transaction.

public record OrderSummary(Long id, String status, List<String> skus) { }
// (3) the fix: fetch what you need and map to a DTO inside the transaction
@Transactional(readOnly = true)
public OrderSummary summary(Long id) {
    Order order = orders.findById(id).orElseThrow();
    return new OrderSummary(order.getId(), order.getStatus(),
            order.getItems().stream().map(OrderItem::getSku).toList());
}
Sources (4)
  1. Spring Boot Reference: Open EntityManager in Viewdocs.spring.io
  2. Hibernate ORM User Guide: Modifying managed/persistent statedocs.jboss.org
  3. Hibernate ORM User Guide: Working with detached datadocs.jboss.org
  4. Hibernate ORM User Guide: Fetching (LazyInitializationException)docs.jboss.org
Previous
Next