Hibernate Entity States - Transient Persistent Detached Removed 4 questions in 2 chapters

  1. 01Entity states in Hibernate3 questions
  2. 02In the real world: Spring Boot

Entity states in Hibernate

  • 1.1 What states can a Hibernate entity be in, and what exactly does each one mean? Easy 3 min

    Per the Hibernate docs, an entity's state depends on two things: whether a persistence context, meaning a Session or EntityManager, knows about it, and whether it has an identifier. Transient means it was just created with new and no context knows it. Managed means it has an identifier and lives in a context. Detached means it has an identifier but the context no longer tracks it. Removed means it's still in the context but scheduled for deletion.

    Read the full answer
  • 1.2 Which operations move an entity between these four states? Medium 5 min

    An entity created with new becomes managed through persist or save. Changes to a managed entity are saved automatically at flush. Closing the context, clear, and evict or detach make it detached, and serialization produces a detached copy. merge copies a detached entity's data onto a new managed instance and returns it. remove makes it removed, and the DELETE runs at flush.

    Read the full answer
  • 1.3 What is the difference between removed and deleted? Medium 2 min

    Removed is a state inside the persistence context: the entity still has its identifier and the context still knows it, it's just scheduled for deletion. Deleted means the DELETE has actually run in the database. Because the persistence context works as a write-behind cache, the DELETE runs at flush, which by default is before commit, and becomes permanent at commit. So there's a gap between calling remove and the row really disappearing.

    Read the full answer

In the real world: Spring Boot

  • 2.1 In Spring Boot, what state is an entity in after a @Transactional method commits? Medium 4 min

    Inside a @Transactional method, the persistence context is bound to the transaction and the entity is managed, so dirty checking works and changes are saved automatically at commit. Once the transaction ends and the context closes, the entity is detached. The exception is open session in view, which is on by default in web apps and keeps the context open until the request ends. That's why I map to DTOs inside the transaction.

    Read the full answer