Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernate HQL Update

 
 

Share on Google+Share on Google+

Hibernate HQL Update

Advertisement
In this section we will discuss HQL update with example.

Hibernate HQL Update

In this section we will discuss HQL update with example.

HQL Update :

Hibernate provides minimal object oriented HQL. It is like SQL. You can perform all SQL operations with HQL like insertion, updating, deletion etc.

In HQL UPDATE clause is used to update existing record of your table by updating one or more properties of your persistent object.
Here is its simple syntax :

String hql = "UPDATE Student stud SET stud.name='" + newName+ "' WHERE stud.name='" + oldName + "'";

You can also write your HQL as :

Query query = session.createQuery("UPDATE Student stud SET name = :newName WHERE name = :oldName");
query.setParameter("newName", "Ron");
query.setParameter("oldName", "Rohnald");
int rowCount = query.executeUpdate();

In this example we are updating name of student by 'Ron' whose name is 'Rohnald'

Your main class code :

package net.roseindia.main;

import net.roseindia.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class MainClazz {

public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
String newName = "Ron";
String oldName = "Rohnald";
try {
Transaction transaction = session.beginTransaction();
String hql = "UPDATE Student stud SET stud.name='" + newName
+ "' WHERE stud.name='" + oldName + "'";
Query query = session.createQuery(hql);

int rowCount = query.executeUpdate();
transaction.commit();
System.out.println("Rows affected: " + rowCount);
session.flush();
} catch (HibernateException e) {

e.printStackTrace();
} finally {
session.close();
}
}
}

Output:

Hibernate: update student set name='Ron' where name='Rohnald'
Rows affected: 1

Download complete source code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 10, 2012

Related Tutorials

Discuss: Hibernate HQL Update  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com