JPA Entity States: New, Managed, Detached, Removed
Fast recall
Quick revision
Core answer
Whether you understand the JPA entity lifecycle and how each state changes the behavior of save/persist/merge/remove
Thinking 'detached' means deleted — detached still exists in the DB; only 'removed' is scheduled for DELETE
Explain that save() on a detached entity triggers a merge (SELECT then UPDATE), not a plain UPDATE
Interview-ready guide
Interview answer
State is about the persistence context, not simply whether id is null. An entity with an assigned UUID can still be new. Closing or clearing the EntityManager detaches managed objects. Detached does not guarantee that a matching row still exists, because another transaction may have deleted it. EntityManager.merge does not reattach the same detached object; it returns a managed copy. Code should continue with that returned value.
JPA Entity States: New, Managed, Detached, Removed
Direct Answer
JPA describes new, managed, detached, and removed entity instances. A new entity has not been made persistent, even if application code has already assigned an id. A managed entity is tracked by a persistence context. A detached entity was managed but no longer is; its database row may still exist, may have changed, or may have been deleted. A removed entity is managed and scheduled for deletion.
Code Example
@Service
public class ProductService {
private final ProductRepository repo;
ProductService(ProductRepository r) { this.repo = r; }
@Transactional
public void lifecycle() {
var product = new Product(null, "Laptop", 1200.0); // TRANSIENT
repo.save(product); // → MANAGED (id assigned)
product.setPrice(1100.0); // tracked, no save() needed
} // tx ends → product is DETACHED
@Transactional
public void delete(Long id) {
var product = repo.findById(id).orElseThrow(); // MANAGED
repo.delete(product); // REMOVED — DELETE at commit
System.out.println(product.getId()); // still readable in memory
}
}
Common Mistakes & Pitfalls
- Detached ≠ removed — detached still exists in the DB; removed is scheduled for DELETE.
- Expecting dirty checking on detached entities — only managed entities auto-sync.
- Assuming save() on detached is a plain UPDATE — it's a merge (SELECT then UPDATE).
- delete() outside a transaction — the entity goes to removed but the DELETE never executes without a commit.
Check your understanding
Answer these without looking back at the article.
- What is the difference between persist() and merge()?
- What happens when a transaction ends to managed entities?
- How does Spring Data's save() decide between persist() and merge()?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.