Different types of Object States in Hibernate - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
 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.
The three states defined by hibernate are:

Transient State
Persistent State
Detached 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.
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() 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.
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.
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.
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
    }
}
 
 
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.
 
 
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().

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 🙂

Difference between update vs merge in Hibernate example
Hibernate cache first level example
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
HQL update, delete Query Example
Hibernate Interceptor Example
Basic Hibernate Example with XML Configuration
Hibernate Composite Key Mapping Example
Hibernate 4 Example with Annotations Mysql
Hibernate session differences between load() and get()
Top 7 Interview Questions in Hibernate
Custom Generator Class in Hibernate
4 ways to create an Object in Java
How to convert Java Object to JSON
How to convert JSON to Java Object Example

Difference between update vs merge in Hibernate example
Hibernate cache first level example
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
HQL update, delete Query Example
Hibernate Interceptor Example
Basic Hibernate Example with XML Configuration
Hibernate Composite Key Mapping Example
Hibernate 4 Example with Annotations Mysql
Hibernate session differences between load() and get()
Top 7 Interview Questions in Hibernate
Custom Generator Class in Hibernate
4 ways to create an Object in Java
How to convert Java Object to JSON
How to convert JSON to Java Object Example
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache