In the previous tutorials, we have discussed complete CRUD operations using hibernate framework. In this tutorial, we are going to discuss 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.

  • Without loading an object from the database
  • Loading an object from the database

Hibernate Update without loading an object :

Usually, if we want to update a record in the 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 the database.

But in hibernate if we know the record id (primary key) we can directly update the record in the database without load or getting the record from the 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 the database.

 

hibernate update example

 

Create Student.java

Student.java
package com.onlinetutorialspoint.pojo;

public class Student implements java.io.Serializable {
package com.onlinetutorialspoint.pojo;

public class Student implements java.io.Serializable {

    private Integer id;
    private String name;
    private Integer rollNumber;

    public Student() {
    }

    public Student(Integer id, String name, Integer rollNumber) {
        this.id = id;
        this.name = name;
        this.rollNumber = rollNumber;
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getRollNumber() {
        return this.rollNumber;
    }

    public void setRollNumber(Integer rollNumber) {
        this.rollNumber = rollNumber;
    }

}

Creating Mapping XML

Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class catalog="onlinetutorialspoint" name="com.onlinetutorialspoint.pojo.Student" table="student">
        <id name="id" type="java.lang.Integer">
            <column name="id"/>
        </id>
        <property name="name" type="string">
            <column length="50" name="name"/>
        </property>
        <property name="rollNumber" type="java.lang.Integer">
            <column name="rollnumber"/>
        </property>
    </class>
</hibernate-mapping>

Main class: HibernteUpdateDemo.java

HibernateUpdateDemo.java
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUpdateDemo {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();

        Student student = new Student();
        student.setId(111);
        student.setName("chandra shekhar");
        student.setRollNumber(8469);
        session.update(student);
        tx.commit();
        session.close();

    }
}

Output:

Console
INFO: Envers integration enabled? : true 
Hibernate: update onlinetutorialspoint.student set name=?, rollnumber=? where id=?

Database :

hibente update example 2

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 the database. We can find the updated details on the above database screenshot.

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.

Session session = factory.openSession();

Transaction tx = session.beginTransaction();

Student student = new Student();
student.setId(111);
student.setRollNumber(8469);
session.update(student);
tx.commit();
session.close();

On the above example, we didn’t set studentName property then null will be updated in the name column in the database.

Hibernate Update with loading an object :

By using this approach, we can update an object with loading the object from the database. We can load the object from the database by calling load() or get() methods. There are some functionality differences between the load() vs get() methods in hibernate. Example :

UpdateDemo.java
package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class UpdateDemo {

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory factory = configuration.buildSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        Student student = session.load(Student.class, 111);
        student.setName("Johnson");
        session.update(student);
        tx.commit();
        session.close();

    }
}

Output :

Console
INFO: Envers integration enabled? : true 
Hibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_, student0_.rollnumber as rollnumb3_0_0_ from onlinetutorialspoint.student student0_ where student0_.id=? Hibernate: update onlinetutorialspoint.student set name=?, rollnumber=? where id=?

Database :

Hibernate update Database

On the above example, we got an object of a 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 whatever we want to update; the other properties will not be affected in the database.

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

Happy Learning 🙂