When to use saveOrUpdate in hibernate
In our earlier post we had covered what exactly saveorUpdate in hibernate does.
Developers that are new to Hibernate constantly calling the saveOrUpdate method whenever a set of changes have been made to a POJO. This isn’t necessary. You only have to associate an instance with the Hibernate Session once within the scope of a transaction. From that point on, you can do whatever you want to your JavaBean instances. Hibernate will persist the final state of your instance when the current transaction is finally committed.
The following piece of code needlessly calls the saveOrUpdate method after instance variables have been updated. This is totally unnecessary, as the User instance was already associated with the Hibernate Session through the original call to saveOrUpdate.
hibernateSession.getTransaction();
User user = new User();
hibernateSession.saveOrUpdate(user);
user.setLoginName(“skg”);
user.setPassword(“skg123″);
hibernateSession.saveOrUpdate(user); //Not recommended//
hibernateSession.getTransaction().commit();
With the first call to saveOrUpdate, the instance named u becomes associated with the Hibernate session. From that point on, you can mess around with the user instance as much as you want, and Hibernate will take care of the persistence. You can initialize, update, change, and modify any instance variable of the user instance that you want, and Hibernate will save the final state of the instance once the transaction has been committed..
hibernateSession.getTransaction();
User user = new User();
hibernateSession.saveOrUpdate(user);
user.setLoginName(“skg”);
user.setPassword(“skg123″);
hibernateSession.getTransaction().commit();
skg








