Wednesday, February 4, 2015

Hibernate Database Update Example

Using Hibernate library We can update a database easily. This post will describe how we can perform update operation on MySQL database.
Before trying to this you have to read my previous tutorial. Im going to update same database used in that tutorial.

Here is the code :
package hibernatetest;

import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
*
* @author Chathura
*/
public class HibernateTest {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Test");
Session session = null;
try{
SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
session.beginTransaction();

String HQL_QUERY ="from Customer customers where customers.customerID = :customerId";
org.hibernate.Query query = session.createQuery(HQL_QUERY);
//Prepared statement
query.setParameter("customerId",5);

for(Iterator it=query.iterate();it.hasNext();){
Customer customer = (Customer) it.next();
customer.setCustomerName("Updated");
}

session.getTransaction().commit();
System.out.println("Done!");
}

catch(Exception e){
System.out.println(e.getMessage());
}

finally{
session.flush();
session.close();
}

}
}

This program will update customer name to "Updated" where customer ID = 5 (Look line 27)

Result :

If you find this is helpful dont forget to leave a comment. Because your comments always encourage me!