hibernate update | hibernate update example | update query

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
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
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.
 
 
Create 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
<?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
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:
INFO: Envers integration enabled? : true 
Hibernate: update onlinetutorialspoint.student set name=?, rollnumber=? where id=?
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 the database. We can find the updated details on the above database screenshot.
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.
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 :
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 :
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 :
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 🙂

Hibernate session differences between load() and get()
Basic Hibernate Example with XML Configuration
hbm2ddl.auto Example in Hibernate XML Config
Different types of Object States in Hibernate
Hibernate 4 Example with Annotations Mysql
Generator Classes in Hibernate
Hibernate Filter Example Xml Configuration
Hibernate Composite Key Mapping Example
HQL update, delete Query Example
Hibernate Native SQL Query Example
Hibernate Named Query with Example
Hibernate Query Language (HQL) Select Operation
Difference between update vs merge in Hibernate example
Hibernate groupby criteria HQL query Example
What is Hibernate

Hibernate session differences between load() and get()
Basic Hibernate Example with XML Configuration
hbm2ddl.auto Example in Hibernate XML Config
Different types of Object States in Hibernate
Hibernate 4 Example with Annotations Mysql
Generator Classes in Hibernate
Hibernate Filter Example Xml Configuration
Hibernate Composite Key Mapping Example
HQL update, delete Query Example
Hibernate Native SQL Query Example
Hibernate Named Query with Example
Hibernate Query Language (HQL) Select Operation
Difference between update vs merge in Hibernate example
Hibernate groupby criteria HQL query Example
What is Hibernate
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache