SPLessons splessons = new SPLessons(); splessons.setId(); (or) SPLessons splessons = null; // In both cases splessons object is Transient State.
For Ex: Session session=new Configuration().configure().buildSessionFactory().openSession(); SPLessons splessons=new SPLessons(); //splessons object is Transient State. splessons.setId(414); Transaction transaction=session.beginTransaction(); transaction.save(splessons); // splessons object is Persistent State. splessons.setId(415); // In this time Id value is effected on DataBase. transaction.commit();
transaction.commit(); session.close(); // Object will goes to Detached State.
When using an update(), Hibernate first checks this object already exists or not in the cache.
If an Id given, already exists, then Hibernate will give the exception called NonUniqueObjectException. If the id doesn’t exist then it will update.
When called merge() and if Id doesn’t exist, then Hibernate will update() and if Id already exists in the Database, object state will be saved in database.
<strong>ClientProgram.java</strong> import org.hibernate.*; import org.hibernate.cfg.*; public class ClientProgram { public static void main(String[] args) { Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); // Transient state_____start Product p=new Product(); p.setProductId(101); p.setProName("iPhone"); p.setPrice(25000); // Transient state_____end // Persistent state_____start Transaction tx = session.beginTransaction(); session.save(p); System.out.println("Object saved successfully.....!!"); tx.commit(); // Persistent state_____end session.close(); factory.close(); } }
see the above client program, where the developer just loaded the object and called the corresponding setter methods, its not related to the database row.
Product p=new Product(); p.setProductId(101); p.setProName("iPhone"); p.setPrice(25000);
Where the developer called save method in the Session Interface, means the object is now having the relation with the database.
session.save(p);
if one want to convert the object from Transient state to Persistent state one can do in 2 ways as follows.