Hibernate Delete Query
In this section we will discuss how to delete record of table using HQL.
Hibernate Delete Query:
Delete query is used to delete the particular record of the table. Hibernate provides you multiple way to delete records. You can delete row by using sql, HQL or by delete() method.
Example : Student is our table and in this example we are going to delete record of student whose roll number is 6.
package net.roseindia.main; import net.roseindia.util.HibernateUtil; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; public class MainClass { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); try { String hql = "DELETE FROM Student stud WHERE stud.roll=:roll"; Query query = session.createQuery(hql); query.setParameter("roll", 6); int rowCount = query.executeUpdate(); if (rowCount == 0) { System.out.println("No data found to delete"); } else { System.out.println("Your record is deleted"); } } catch (HibernateException e) { e.printStackTrace(); } finally { session.close(); } } }
You can also use delete() to delete the record. Here is main class code. Just take a over view and download complete code from the given link.
package net.roseindia.main; import net.roseindia.table.Student; import net.roseindia.util.HibernateUtil; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class HibernateDelete { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); try { Transaction transaction = session.beginTransaction(); int roll = 2; Object object = session.load(Student.class, roll); session.delete(object); transaction.commit(); System.out.println("Student record of Id=" + roll + " is deleted successfully"); } catch (HibernateException e) { e.printStackTrace(); } finally { session.close(); } } }
Here is output of your code:
Hibernate: select student0_.roll_no as roll1_0_0_, student0_.course as course0_0_, student0_.name as name0_0_ from student student0_ where student0_.roll_no=? Hibernate: delete from student where roll_no=? Department record of Id=2 is deleted successfully