There may be times where you want to retrieve data from DB, do some changes in it and save back the data.In such a time the connection could not be kept open for the whole period of time since db connections are resource intensive.
So I will fetch the object -> close the Session -> Do some operations -> Open new session again -> Update the Object -> Close the Session.
sessionFactory = createSessionFactory(); Session objSession = sessionFactory.openSession(); objSession.beginTransaction(); Users objUser = objSession.get(com.mugil.user.Users.class, 11); objSession.getTransaction().commit(); objSession.close(); objUser.setUserName("Updated"); objSession = sessionFactory.openSession(); objSession.beginTransaction(); objSession.update(objUser); objSession.getTransaction().commit(); objSession.close();
Now the way Hibernate works is it first runs the select query for the value which should be changed and updates the value.So 2 queries for the whole process.Now there are chance’s the value fetched from DB may or may not be changed.So we can do a check which checks the fetched and updated value for uniquess before running the update query.If the fetched data is not changed th update query wont be run.
The Annotation for that is as below.
@Entity @org.hibernate.annotations.Entity(selectBeforeUpdate=true)