Wednesday, 26 December 2012

Free Hibernate Database Update Example


By on 23:18

Using Hibernate library We can update a database easily. This post will describe how we can perform update operation on MySQL database.

Here is the code :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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 don't forget to leave a comment. Because your comments always encourage me!

About Syed Faizan Ali

Faizan is a 17 year old young guy who is blessed with the art of Blogging,He love to Blog day in and day out,He is a Website Designer and a Certified Graphics Designer.

0 comments:

Post a Comment