Tuesday 22 May 2018

What are different states of an entity bean in Hibernate?

       In previous post, learned the Hibernate - JPA Annotations with explanation and One to One mapping examples.   In this we will learn the status of entity bean in Hibernate.

In Hibernate, there are three states of entity bean,

  • Transient
  • Persistent
  • Detached

         1) Transient
       When ever we create a new object of Entity bean then we can say that is in Transient state, At that time any modification in the object state does not effect on database.

             2)  Persistent 

      When ever the Object of entity bean associated with session we can say that is in persistent state, if any change in the object state , then that modification effects in database.

            3) Detached

     When ever the object is removed from session then it enters in to detached state. Any modification on detached state object , does not effect in database.


package com.test;
public class Student {
      private int studentId;
      private String studentName;
      private String standard;
      public int getStudentId() {
           return studentId;
      public void setStudentId(int studentId) {
           this.studentId = studentId;
      public String getStudentName() {
           return studentName;
      public void setStudentName(String studentName) {
           this.studentName = studentName;
      public String getStandard() {
           return standard;
      public void setStandard(String standard) {
           this.standard = standard;

class EntityState {

    public static void main(String[]args) {

         SessionnFactory factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactpry();
         Sessiion session1=factory.openSession(); 
         // Entity bean in Transient state.
         Student s = new Student();    
         Transaction tx1=session1.beginTransaction();
         // Entity in Persistent State.

         // Now s becomes detached, this is detached state
         s.setStandard(8);; //  Will not effect in db

Related Post:
1) Hibernate One to One Mapping Example - Annotation based
2) Hibernate - JPA Annotations with explanation
3) Advantages of Hibernate over JDBC
4) What are the Core Interfaces of Hibernate framework ?
5) Spring MVC with Hibernate CRUD Example

No comments:

Post a Comment