An entity’s state describes its relationship to a persistence context during a unit of work. A persistent instance is managed by that context and has a database representation—or will have one when the unit of work completes. The context tracks changes for persistence synchronization. section 10.1 section 10.1.1
The lifecycle has four states:
- Transient: created with `new` and not yet made persistent. `EntityManager.persist()` or an enabled cascade can move it into persistent state. section 10.1.1
- Persistent: associated with a persistence context. A query, identifier lookup, or navigation from another managed instance can also produce a persistent instance. section 10.1.1
- Removed: marked for deletion through `EntityManager.remove()` or orphan removal on a mapped collection. section 10.1.1
- Detached: no longer managed, for example after `EntityManager.detach()` or context closure. Changes made while detached do not update the database unless merged into a new context. section 10.3.3
Making an Item persistent
Within a unit of work: `Item item = new Item(); item.setName("Some Item"); em.persist(item);` The call associates `item` with the current persistence context. Hibernate normally issues the `INSERT` when the transaction commits and the context flushes, though an identifier generator may require an immediate insert. section 10.2.2
Use `em.contains(entity)` to check whether an instance is managed by that context. An identifier can help distinguish transient from detached instances, but identifier assignment may wait until flush; primitive identifier properties also require care. Avoid basing `equals()` and `hashCode()` solely on a generated identifier: its change on persistence can break a `Set`. section 10.2.2 section 10.3.2
The state-transition diagram provides a quick map of the four lifecycle states and their transitions. section 10.1.1
