Junior — Middle
What methods do you use to manage the lifecycle of objects in Hibernate?
sobes.tech AI
Answer from AI
In Hibernate, the management of object lifecycle is carried out using various methods and entity states:
- save() / persist() — save a new object to the database, transitioning it to the "managed" (persistent) state.
- update() / merge() — update an existing object or merge the state of a detached object with the current context.
- delete() — remove an object from the database.
- evict() — remove an object from the session, transitioning it to the "detached" state.
- refresh() — update the state of an object from the database.
The object lifecycle in Hibernate includes the states: transient (temporary, not associated with a session), persistent (managed by the session), detached (disconnected from the session).
Example:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
// Creating and saving an object
User user = new User();
user.setName("John");
session.save(user); // object becomes persistent
// Updating the object
user.setName("John Doe");
session.update(user);
// Deleting the object
session.delete(user);
tx.commit();
session.close();
Thus, Hibernate methods allow controlling the state of objects and their synchronization with the database.