Detached Entity and Managed Entity

Shemil picture Shemil · Dec 9, 2011 · Viewed 25.1k times · Source

What a "detached entity" means? How is it possible to convert a managed entity to a detached entity during a transaction?

Answer

Piotr Nowicki picture Piotr Nowicki · Dec 9, 2011

A detached entity is an entity which state must not be reflected by the JPA provider.

In other words, if you change its state (i.e. through setters methods) these changes will not be saved to the underlying database, as the JPA provider doesn't have to "observe" such entities.

If entity E1 is a managed entity you can make it detached invoking (very reasonable named) method EntityManager#detach(E1). You can also use EntityManager#clear() which will clear whole PersistenceContext and effectively making all managed entities detached.