Java and Spring Level 1 This level · 17 of 105
Easy java hibernate

What states can a Hibernate entity be in, and what exactly does each one mean?

The 30 second answer

Per the Hibernate docs, an entity's state depends on two things: whether a persistence context, meaning a Session or EntityManager, knows about it, and whether it has an identifier. Transient means it was just created with new and no context knows it. Managed means it has an identifier and lives in a context. Detached means it has an identifier but the context no longer tracks it. Removed means it's still in the context but scheduled for deletion.

Could you say this in an interview?

The Hibernate docs say that both the Session and the EntityManager represent a persistence context, and that persistent data has a state in relation to both that context and the underlying database. There are four official states:

  • transient (Jakarta Persistence also calls it new): the entity has just been instantiated and is not associated with a persistence context. It has no persistent representation in the database, and typically no identifier value has been assigned yet, unless the assigned generator was used.
  • managed or persistent: the entity has an identifier and is associated with a persistence context. It may or may not physically exist in the database yet, for example when it has been persisted but not flushed.
  • detached: the entity has an identifier but is no longer associated with a persistence context, usually because the context was closed or the instance was evicted from it.
  • removed: the entity has an identifier and is still associated with a persistence context, but it is scheduled for removal from the database.

The key point for the interview: the state depends on the persistence context, not on whether the row exists. A detached entity can have a row, and a managed entity may not have a row yet.

Code: the example domain used on this page. An Order with a couple of fields and one lazy association. @OneToMany is LAZY by default, which is what makes the detached-state failure visible later.

import jakarta.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "orders")
public class Order {

    @Id
    @GeneratedValue
    private Long id;

    private String customer;

    private String status;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) // LAZY by default
    private Set<OrderItem> items = new HashSet<>();

    protected Order() { }

    public Order(String customer) {
        this.customer = customer;
        this.status = "NEW";
    }

    public void addItem(OrderItem item) {
        items.add(item);
        item.setOrder(this);
    }

    public Long getId() { return id; }
    public String getCustomer() { return customer; }
    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }
    public Set<OrderItem> getItems() { return items; }
}
import jakarta.persistence.*;

@Entity
public class OrderItem {

    @Id
    @GeneratedValue
    private Long id;

    private String sku;

    @ManyToOne(fetch = FetchType.LAZY)
    private Order order;

    protected OrderItem() { }

    public OrderItem(String sku) { this.sku = sku; }

    public String getSku() { return sku; }
    void setOrder(Order order) { this.order = order; }
}
import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderRepository extends JpaRepository<Order, Long> { }

The service methods in the next questions live in this class:

@Service
public class OrderService {

    private final OrderRepository orders;

    @PersistenceContext
    private EntityManager em;   // only needed for merge, remove and contains below

    public OrderService(OrderRepository orders) { this.orders = orders; }
    // methods below
}
Sources (1)
  1. Hibernate ORM User Guide: Persistence Context (entity states)docs.jboss.org
Previous
Next