Hibernate HQL Update

In this section we will discuss HQL update with example.

Hibernate HQL Update

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