HQL Delete Query hibernate

HQL Delete Query hibernate

You could use HQL to delete data form the table and its almost same as native SQL query except in place on table and column name you have to use class name and its attribute name.

Note: This class is extension of previous tutorial. If you are interested to see full working example with all set up please refer this tutorial Hibernate One To Many Annotation Example

Please have java example below:

package com.javahonk;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.javahonk.util.HibernateUtil;

public class DeleteQuery {
    
    static SessionFactory sf = HibernateUtil.getSessionFactory();

    public static void main(String[] args) {

        Session session = sf.openSession();
        session.beginTransaction();

        System.out.println("Delete query example\n");

        Query query = session.createQuery("delete Child "
                + "where childId = :childId");
        
        query.setInteger("childId", 3);
        
        int noOfRowsDeleted = query.executeUpdate();        

        System.out.println("Total no of rows deleted: "
                        +noOfRowsDeleted);

        session.getTransaction().commit();
        session.close();

    }
}

Output:

HQL Delete Query hibernate

 

For more information about HQL please read this hibernate official tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *