hibernate update query example

In the previous tutorials we have discussed about complete CRUD operations using hibernate framework. In this tutorials we are going to discuss about what are the different ways to update an object using hibernate. And we can also conclude that which method is better than all the approaches.

Hibernate Update :

We can update an object in hibernate by calling the update() method, provided by the org.hibernate.Session. Though the update() method is used to update an object, there are two different ways to use update() method.

With out loading an object from database

Loading an object from database

Hibernate Update with out loading an object :

Usually if we want to update a record in database, first of all we should get that record and manipulate and save it to the database. it is a usual practice of updating the record in database.

But in hibernate if we really know the record id (primary key) we can directly update the record in database with out load or getting the record from database.

If we know the record id, then we can directly create a new object and assign the primary key to it and save using update() method.

Example : In this example I am going to update the below 111 student object in database.

Database :By running the above application, we can update the student details using hibernate update method. Based on the Id property (primary key) hibernate will update the details in database. we can find the updated details on the above database screen shot.

Problem with This approach :

A problem with this approach is, we must set all the properties of an object. If we don’t set any one of the property then its default values (null) will be updated in the database.

Database :On the above example, we got an object of student by calling load() method. On that object we can make the changes and update by calling update() method. But for this approach we no need to set all the properties of a student. We can only set what ever we want to update, the other properties will not effected in the database.

From the above two approaches, second one (Hibernate update with loading an object) is recommended approach, because here we no need to set all the properties. Based on our requirement we can update the values as we want.

Hi
Folks,
you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,