What states can an object have in Hibernate?
sobes.tech AI
Answer from AI
In Hibernate, an object can be in one of the following states:
-
Transient: The object is created using the
newoperator but is not yet associated with a Hibernate session. It has no corresponding record in the database.// Transient state User user = new User(); user.setName("John Doe"); -
Persistent: The object is associated with an active Hibernate session. Any changes made to the object will be synchronized with the database upon transaction commit or flush. It has a corresponding row in the database.
// Transition from Transient to Persistent session.save(user);Changes in a Persistent object are tracked:
// Modification of a Persistent object user.setEmail("john.doe@example.com"); // Changes will be persisted -
Detached: The object was previously Persistent, but its session was closed or the object was explicitly detached (
session.evict(object)). It is not associated with an active session, and changes will not be automatically synchronized with the database.// Transition from Persistent to Detached session.close(); // Or session.evict(user);To save changes to a Detached object, it must be reattached to a session:
// Reattaching a Detached object session.update(user); // Or session.merge(user);
Summary table of states:
| State | Session association | Database correspondence | Change tracking | How to obtain/transition |
|---|---|---|---|---|
| Transient | No | No | No | new YourClass() |
| Persistent | Yes | Yes | Yes | session.save(), session.get(), session.load(), session.createQuery().list() |
| Detached | No | Yes | No | session.close(), session.evict(), session.clear() |