Hibernate Delete Query

In this lesson we will show how to delete rows from the underlying database using the hibernate.

Hibernate Delete Query

Hibernate Delete Query

     

In this lesson we will show how to delete rows from the underlying database using the hibernate. Lets first write a java class to delete a row from the database.

Create a java class:
Here is the code of our java file (
DeleteHQLExample.java), which we will delete a row from the insurance table using the query "delete from Insurance insurance where id = 2"

Here is the code of delete query: DeleteHQLExample.java 

package roseindia.tutorial.hibernate;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DeleteHQLExample {
  /**
 @author vinod Kumar
 
 * http://www.roseindia.net Hibernate
 Criteria Query Example

 *  
 */
  public static void main(String[] args) {
  // TODO Auto-generated method stub  
  Session sess = null;
  try {
  SessionFactory fact = new 
Configuration
().configure().buildSessionFactory();
  sess = fact.openSession();
  String hql = "delete from 
Insurance insurance where id = 2"
;
  Query query = sess.createQuery(hql);
  int row = query.executeUpdate();
  if (row == 0){
  System.out.println("Doesn'
t deleted any row!"
);
  }
  else{
  System.out.println("Deleted
 Row: " 
+ row);
  }
  sess.close();
  }
  catch(Exception e){
  System.out.println(e.getMessage());
  }
  }
}

Download this code.

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: delete from insurance where ID=2

Deleted Row: 1