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
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
how to fetch data from multiple tables using createcriteria in CRUD operations???
We no need to call updated() method explicitly here just following line code is enough to update the user entity
user = (UserDetails) session.get(UserDetails.class, 2); user.setUserName(“Sweety”);
session.getTransaction().commit();
change the color …
change the color code…