Video in progress

Explain the entity lifecycle states: transient, managed, detached and removed.

Transient is an object created with new that Hibernate doesn't know about. Managed is an object the persistence context is tracking. Detached was managed before, but its context was closed or the object was detached from it. Removed is marked for deletion and gets a DELETE on flush.

📖 Answer

Here are all of them in one example:

@Transactional
public void demo() {
    User u = new User("ali");   // transient: no id, nobody is tracking it
    em.persist(u);              // managed: changes are now tracked
    u.setName("Ali");           // UPDATE on flush (or folded into the INSERT)

    em.detach(u);               // detached: changes no longer go to the database
    u.setName("Vali");          // nothing happens

    User m = em.merge(u);       // m is a managed copy again
    em.remove(m);               // removed: DELETE on commit
}

In practice, the detached state you meet most often is an entity returned to the controller after the transaction has ended. If you touch its lazy fields you get LazyInitializationException, and if you change it, nothing is saved.

To check the state, there is em.contains(entity), which returns true if the entity is managed. It helps a lot when debugging.