Home Hibernate Hibernate HQL Update



Hibernate HQL Update
Posted on: July 10, 2012 at 12:00 AM
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

Related Tags for Hibernate HQL Update:


More Tutorials from this section

Ask Questions?    Discuss: Hibernate HQL Update  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.