Object states in Hibernate play a vital role in the execution of code in an application. Hibernate has provided three different states for an object. These three states are also called as hibernate’s life cycle states of an object.
Object States in Hibernate :
The three states defined by hibernate are:
- Transient State
- Persistent State
- Detached State
Transient State :
An object that is created for the first time using the new() operator, then it is under the state of Transient. As it is a newly created object, it doesn’t have any connection with the Hibernate Session.
This object becomes persistent when it is mapped with a database or an identifier value. It means, when we save an object, initially the object being added to the cache. This state is considered to be a persistent state.
A Transient object can be destroyed automatically by the garbage collector if any active session object is not referring to it.
Persistent State :
The state of an object is being associated with the hibernate session is called a Persistent state. The Persistent object represents the database entity, and its unique identifier value represents the database table primary column.
The values associated with the persistent object are sync with the database. It means, if we change the values in persistent state objects, the changes will automatically get affected in the database, no need to execute insert/update operations.
On the above diagram, the student is created for the first time using a new() , then the object is in a Transient state. This object is get converted to Persistent state, once the student object attached with the session.save() method.
In place of session.save(), we can also use session.persist(). Both these methods result in SQL INSERT.
The differences between the two functions are as follows:
Save():
- Save() method is used to save entities to the database immediately.
- This method can be invoked from both inside and outside a function.
- Save() method returns a Serializable object.
- If the database table already contains a primary key, save() function will not update its values.
- It is not useful for long-running conversations.
Persist() :
- Like Save(), Persist() is also used to save entities to the database.
- Persist() executes only within a method. It will not execute if it is called outside a method.
- This method does not return any value.
- This method coverts a transient instance to a persistent instance.
- Persist() is beneficial in long-running conversations.
Detached Object State :
The object can go into the detached state when we close the session.
We can detach an object from the session by using the three mechanisms.
- session.clear();
- session.evict(student);
- session.close();
session.clear() will clear all the objects which are associated with the specified session. Whereas session.evict(student) will only delete the student object from the session object.
session.close() is used to close the session while closing the session all the objects from the session will be removed.
Hibernate Object States Example :
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class ObjectStatesDemo {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
// Transient State
Student student = new Student();
student.setId(101);
student.setName("chandrashekhar");
student.setRollNumber(10);
Transaction transaction = session.beginTransaction();
// Going to Persistent State
session.save(student);
student.setName("Goka"); // Updated in database
transaction.commit();
session.close();
// Detatched state
student.setRollNumber(40); // Not Updated in Database
}
}
Methods used to Hibernate Object state transition :
Here are different methods, used to alter the hibernate object states.
save(), persist() and saveOrUpdate() methods are used to take the transient state object to persistent state.
Whenever we get the data from the database using get() or load() methods, the data would be in the persistent state only.
close(), evict(), and clear() methods are used to take the hibernate persistent object state to detached state.
Reattach Detached objects in Hibernate :
The update() and merge() methods are used to reattach the detached objects to a session. Both will do the same thing, but there are some significant differences between update() and merge().
Reattaching the Detached Objects Example :
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateStatesExample {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
// Transient State
Student student = new Student();
student.setId(111);
student.setName("chandrashekhar");
student.setRollNumber(10);
Transaction transaction = session.beginTransaction();
// Going to Persistent State
session.save(student);
student.setName("Goka"); // Updated in database
transaction.commit();
session.close();
// Detatched state
Session session2 = factory.openSession();
Transaction transaction2 = session2.beginTransaction();
session2.update(student); // reattaching
student.setRollNumber(40); // Updated in Database
session2.evict(student); // Detaching student object from session
student.setId(300); // not update to Database.
Student student2 = session2.get(Student.class, 111);
student2.setRollNumber(500); // Updated in Database
session2.update(student2);
transaction2.commit();
session2.close();
}
}
Happy Learning 🙂