What are the entity states in Hibernate?
sobes.tech AI
Answer from AI
In Hibernate, an entity can be in one of the following states:
-
Transient: The object is created but not associated with a Hibernate session. It has no representation in the database. Operations on it are performed in memory but do not affect the database.
// Student entity is created but not attached to a session Student student = new Student("Ivan", "Ivanov"); -
Persistent: The object is associated with the current Hibernate session and managed by it. Any changes to the object will be synchronized with the database upon transaction commit or session flush. An object retrieved from the database using a session is in this state.
// Student entity is retrieved from or saved to the database Session session = sessionFactory.openSession(); session.beginTransaction(); Student student = new Student("Petr", "Petrov"); session.save(student); // student is now in Persistent state // Or // Student student = session.get(Student.class, 1L); // student in Persistent state session.getTransaction().commit(); session.close(); -
Detached: The object was previously associated with a session, but the session was closed or the object was explicitly detached (e.g., using
session.evict(object)). The object still contains data from the database, but changes made to it will not be automatically synchronized with the database. To save changes, the object needs to be re-attached to another session.Session session1 = sessionFactory.openSession(); session1.beginTransaction(); Student student = session1.get(Student.class, 1L); // Persistent session1.getTransaction().commit(); session1.close(); // student is now Detached // Modifying the object in Detached state does not affect the database student.setName("New Name"); // To save changes, re-attach to a new session Session session2 = sessionFactory.openSession(); session2.beginTransaction(); session2.update(student); // student becomes Persistent again session2.getTransaction().commit(); session2.close();
Transitions between states:
| From/To State | Transient | Persistent | Detached |
|---|---|---|---|
| Transient | (remains) | save(), persist(), saveOrUpdate() |
(not directly possible) |
| Persistent | (not possible) | (remains) | close(), evict(), clear() |
| Detached | (not possible) | update(), merge(), saveOrUpdate() |
(remains) |