April 30 2015

Hibernate object states – Transient,Persistent and Detached

Hibernate object states

The following are the hibernate object states

Transient object state

An object which is not associated with hibernate session and does not represent a row in the database is considered as transient. It will be garbage collected if no other object refers to it.

You have to use save, persist and saveOrUpdate methods to persist the transient object.

Persistent object state

An object which represents a row in the database or a transient object which is associated with session is considered as persistent object. It is the existing object which is retrieved from database or a transient object associated with session and which is about to be saved.

Changes made to the persistent object are detected and saved to database when the transaction is committed.

Detached object state

An object which represents a row in the database and not associated with active session is considered as detached object. When you close the session to which the object is associated the persistent object will become detached object.

Any changes made to the detached objects are not saved to the database. The detached object can be reattached to the new session and save to the database using update, saveOrUpdate and merge methods.

Example

package com.answersz.dao;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

// Hibernate object states
public class HibernteObjectStates {

public static void main(String[] args) {

// Transient object state
Student s1 = new Student();
s1.setStudentName("HARRY");
s1.setFatherName("CHARLIE");
s1.setDateofBirth(new Date());
s1.setCourse("MTECH");
// Transient object state

SessionFactory factory = new AnnotationConfiguration().configure()
.buildSessionFactory();

Session session = factory.openSession();

Transaction t = session.beginTransaction();

// Persistent object state
session.save(s1);
s1.setCourse("MTECH");
t.commit();
// Persistent object state

session.close();

// Detached object state
s1.setFatherName("GEORGE");

factory.close();

}

}

Output

Hibernate: insert into student (COURSE, DATE_OF_BIRTH, FATHER_NAME, STUDENT_NAME) values (?, ?, ?, ?)

Table

select * from student;

STUDENT_ID STUDENT_NAME FATHER_NAME DATE_OF_BIRTH COURSE
945 HARRY CHARLIE 4/30/2015 MTECH
 


Copyright © 2014. All rights reserved.

Posted April 30, 2015 by answersz in category Hibernate

Leave a Comment

Your email address will not be published. Required fields are marked *

*