Hibernate Update Query

In this tutorial we will show how to update a row with new information by retrieving data from the underlying database using the hibernate. Lets first write a java class to update a row to the database.
Create a java class:

here we update the value of the field name userName with corresponding column name is USER_NAME in the database table USRE_TABLE.

In the above table we want to update the value of the USER_NAME column of the USER_TABLE table associated user model object which userId = 2
current value of the userName is ‘Anamika Rajput’ update to userName=’Sweety’.
Look the following class file.
HibernateTestDemo.java

package com.sdnext.hibernate.tutorial;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.sdnext.hibernate.tutorial.dto.UserDetails;

public class HibernateTestDemo {
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        UserDetails user = null;
   
 SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
       
        user = (UserDetails) session.get(UserDetails.class, 2); //Retrieving object which we want to update
        user.setUserName(“Sweety”); //Set the updated userName to the model field
        session.update(user); //Update to the database table
        session.getTransaction().commit();

        System.out.println(“Updated User ->”+user);
   
      session.close();
    }
}

Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select userdetail0_.USER_ID as USER1_0_0_, userdetail0_.USER_NAME as USER2_0_0_ from USER_TABLE userdetail0_ where userdetail0_.USER_ID=?
Hibernate: update USER_TABLE set USER_NAME=? where USER_ID=?
[Updated User -> User Name: Sweety User Id: 2]

Now we get the following updated table…

We are looking the value of the USER_NAME column updated from ‘Anamika Rajput‘ to ‘Sweety‘ in the USER_TABLE table.

Now in the Next Chapter we will see how to delete a row in the hibernate.


                                        <<Previous Chapter 10<<    >>Next Chapter12

View Comments