Newsletter

Hibernate Converting Object From Detached to Persistent state

Hibernate » on Jun 19, 2011 { 19 Comments } By Sivateja

Now we will see, how to convert the detached state object into Persistent state again…,
As usual hibernate configuration, mapping XML are same and pojo class too, if you want just refer Hello World Program

ClientLogicProgram.java:

import org.hibernate.*;
import org.hibernate.cfg.*;

public class ClientLogicProgram {

    public static void main(String... args)
    {

        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");

        SessionFactory factory = cfg.buildSessionFactory();

        Session session1 = factory.openSession();

         Product p=null;          //Transient state..
         Object o=session1.get(Product.class, new Integer(1001));
         p=(Product)o;           //now p is in Persistent state..

        session1.close();

        p.setPrice(36000);            // p is in Detached state

        Session session2=factory.openSession();

         Transaction tx=session2.beginTransaction();
            session2.update(p);      // now p reached to Persistent state
         tx.commit();

        session2.close();

        factory.close();
}
}

Notes:

  • We have opened the session1 at line number 14 and closed at line number 20, see i have been loaded the Product class object by using get(-,-) method
  • Remember get() method always returns the super class object (Object)
  • so i typecast into my pojo class object type, so now we can use print any value from this object so its in the Persistent state
  • see line number 22,  am trying to change the Price,  but it wont effect the database because its not in the session cache so i need to take one more session to update this value in the database, so for that reason i took one more session from line numbers 24 – 30
  • Gun short point is, things related to database must go with in the session only that’s it

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

19 Responses to “Hibernate Converting Object From Detached to Persistent state”
  1. Mohammed Vaseem says:

    Hello Java4s.

    Am getting error in this program, I think in line numbers 18,22,27 instead of s reference variable “p” should come.

    If i replace s with p, then no compilation errors. But when executing am getting an exception at line 22(I think NullpointerException). Please clarify this.

    Thanks in Advance…

  2. Java4s says:

    @ Vaseem

    Thank you vaseem, its ‘p‘ not ‘s‘, code updated.

    And change line number 27 session2.update(p);

    to

    session2.merge(p);
    And check.

  3. Mohammed Vaseem says:

    Thank you for your extreme help java4s ….
    I did not found no tutorial on the internet with this much of support…

  4. Mohammed Vaseem says:

    Hello Java4s, I updated the text where you directed but am still getting error in this program at line 22.
    Am Showing the last lines of my console.

    INFO: schema update complete
    Hibernate: select product0_.pid as pid0_0_, product0_.pname as pname0_0_, product0_.price as price0_0_ from urPRODUCTS product0_ where product0_.pid=?

    Exception in thread “main” java.lang.NullPointerException
    at ClientLogicProgram.main(ClientLogicProgram.java:22)

    Please help. Thanks in Advance..

  5. saranya says:

    what is the difference b/w get() and load() becs both are returning Object?

  6. Harikrishna says:

    even if we use update we can able to update the persistenet object,at line 27 merge is not required can any one tell me major difference between merge and update where they should be used

  7. Chetan says:

    Nice tutorial………….for java bie

  8. chakri says:

    1).load() loads an object from database lazily.But get() read an object from database early.
    2.)when we call call load() then it will not goto database immediately.But when we call get() then it will go to database read the data and return the object.
    3).when we are reading or loading an object from database if given id is not exist in database it will throws OBJECTNOTFOUNDEXCEPTION.But get() throws only NULL.

  9. Satwick says:

    Hi..
    Can you please add the concept of locking Mechanism

  10. Dinesh says:

    Nice articles with good explanation, Keep going…

  11. Tanzeem Sayed says:

    Very Nice tutorials for beginners, please post some important tutorials on multithreading..

  12. Vishnu says:

    Am getting null pointer exception while executing above program…please tell me what is happening exactly and why it is showing nullpointer exception

  13. Srini Vas says:

    check ur db properties in cfg.xml file

  14. Rinky Arora says:

    Hi,

    I am getting error : org.hibernate.LazyInitializationException: could not initialize proxy – the owning Session was closed

    while executing the below code :

    public static void main(String args[])
    {
    Configuration cfg= new Configuration();
    cfg.configure(“hibernate.cfg.xml”);

    SessionFactory factory= cfg.buildSessionFactory();
    Session session=factory.openSession();

    org.hibernate.Transaction transaction=session.beginTransaction();

    try
    {

    Employee_Info emp1=null;
    emp1=(Employee_Info)session.load(Employee_Info.class, new Integer(1));
    session.close();

    emp1.setSalary(1200);

    Session session2=factory.openSession();

    org.hibernate.Transaction transaction2=session2.beginTransaction();
    session2.update(emp1);
    transaction2.commit();

    session2.close();

    factory.close();
    }
    catch(Exception e)
    {
    System.out.println(“EXCEPTION…………”+e);
    try {
    //transaction.rollback();
    } catch (IllegalStateException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    }

    }

  15. Tanweer says:

    you are just awesome man..your way of explaining z jst amazing.u r god of Java..

  16. Dhiraj Kumar says:

    Sir, can u please explain that what will happen if we will call the object using load() method in line 17? because i m getting an exception.

  17. Aslam a says:

    Hi
    Please update the code, change session2.update(p) to session2.merge(p);
    Anyone can be easily mislead.
    Thanks.

  18. Abhishek says:

    Hi Sir,
    I am so glad to read your hibernate tutorial. Its quite easy to understand and very simple to learn since the way you have explained, its awesome. Now I can learn hibernate with confidence without deviating myself to any other hibernate tutorial link. Thanks so much sir for your effort to prepare such a nice tutorial. My best wishes are always with you.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.