hibernate State

hibernate State

https://www.baeldung.com/hibernate-session-object-states

https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate


The Session interface is the main tool used to communicate with Hibernate

transient

An object we haven't attached to any *session* is in the transient state.

persistent

An object that we've associated with a *session* is in the persistent state

Persist or save : Alternatively, we may use the save method. The difference is that the persist method will just save an object, and the save method will additionally generate its identifier if that's needed.

detached

When we close the session, all objects inside it become detached. Although they still represent rows in the database, they're no longer managed by any *session*:


Screen Shot 2020-11-26 at 11.50.58 AM

When the entity instance is in the persistent state, all changes that you make to the mapped fields of this instance will be applied to the corresponding database records and fields upon flushing the Session. The persistent instance can be thought of as “online”, whereas the detached instance has gone “offline” and is not monitored for changes.

This means that when you change fields of a persistent object, you don't have to call save, update or any of those methods to get these changes to the database: all you need is to commit the transaction, or flush or close the session, when you're done with it.

Merge

After deserializing this entity instance, you need to get a persistent entity instance from a persistence context and update its fields with new values from this detached instance. So the merge method does exactly that:

  • finds an entity instance by id taken from the passed object (either an existing entity instance from the persistence context is retrieved, or a new instance loaded from the database);
  • copies fields from the passed object to this instance;
  • returns newly updated instance.