Hibernate Converting Object From Detached to Persistent state
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:
12345678910111213141516171819202122232425262728293031323334import 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
post a comment