Wednesday, November 18, 2015

Hibernate Update Query

Hibernate Update Query

This is the program to update an object (1 complete row) in the database, which is already persisted in the database, then we have the following two approaches…

Approach 1

Load that object from the database, and modify its values, now hibernate automatically modifies the values on to database also, when ever the transaction is committed.

Approach 2:

If we want to modify object in the database, then create new object with same id and we must call update() given by session interface.
Files required to execute this program..
  • Product.java (My POJO class)
  • product.hbm.xml (Xml mapping file )
  • hibernate.cfg.xml (Xml configuration file)
  • ClientProgram.java(java file to write our hibernate logic)

Related to approach 1:

Product.java (POJO)



Product.hbm.xml



hibernate.cfg.xml



ClientProgram.java (* Recommended way)


Notes:
  • See line number 20, actually there i tried to update Stno(105), we should not do this, because we have loaded the object from the database with his id number only, see line number 16, if we update hibernate will rises the exception
  • See line number 24 once we call the commit(), automatically update method will be called by hibernate.
  • When ever an object is loaded from the database then hibernate stores the loaded object in cache-memory maintained by session-interface
  • Once an object is loaded, if we do any modifications on that object by calling its setter methods, then these modification are stored in the object maintained by cache-memory
  • if we modify the loaded object for multiple times then also the modifications will be stored in object maintained by the cache-memory only.
  • when ever we issue commit() operation then hibernate verify whether any changes are there between the object stored in the cache and object in the database, if changes exists then hibernate automatically updates the database by generating any update operation.
  • What am saying is hibernate automatically maintains synchronization between cache-memory object and database table objects (rows)

Related to approach 2:



Oracle DB, Before Run The Program

Oracle DB, After Run the program

Notes:
  • From line number 17 to 19, we created new object and modified, and in line number 22 we are calling update method explicitly
  • Here we no need to load an object from the database
  • we will create a new object, and we will assign same id no’s to it and we will call update() explicitly in order to make the changes on the object that is stored in the database

That’s it, actually first approach is  recommended always..   :-)

No comments:

Easy Way to Handle Android Notifications

Android Notifications Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persist...