Video in progress
When does the "detached entity passed to persist" error occur, and how do you fix it?
When you pass persist() an object that has an id set but isn't in the context: Hibernate considers it detached. It often appears through cascade PERSIST, when a child that already exists in the database (say, one that came in the request with an id) is passed along with a new parent.
📖 Answer
A typical case:
@Transactional
public Order create(CreateOrderRequest req) {
Order order = new Order();
Customer c = new Customer();
c.setId(req.customerId()); // exists in the database, but this is a new object
order.setCustomer(c);
em.persist(order); // with cascade PERSIST: error
return order;
}
Order.customer has cascade = CascadeType.ALL. Hibernate passes persist on to the customer too; it has an id, and with a generated id strategy "has an id" means "already saved". It isn't in the context, so it's detached.
The fix:
- Remove the cascade from the
@ManyToOne. Creating a child through its parent makes sense on the@OneToManyside; on a@ManyToOneyou almost never need cascade. - Get a managed object for the association:
order.setCustomer(em.getReference(Customer.class, req.customerId()));
If the object really is detached and needs updating, use merge(), but carry on with the object it returns.
A similar case: saving one object twice in a test, or calling persist again on the same entity after a @Transactional test has ended. The message is the same, and the cause is that the context changed.
Sign up to mark studied questions and save your progress.