Hibernate delete Query

In this tutorial you will learn how to use HQL delete query in Hibernate.

Hibernate delete Query

Hibernate delete Query

In this tutorial you will learn how to use HQL delete query in Hibernate.

In this section we are discussing about the HQL delete query of Hibernate. Here we will give an example which will demonstrate you how to use HQL delete query. An example is being given regarding how delete query may be used in programs. At first we must know about the delete query, delete query is used to delete the fields, field records, table, etc. In our example we will delete the field's record. To do so at first I have created a table named salesorder with 'id', 'price', and 'purchaser' fields that contains some records. Then created a POJO class named SalesOrder, a mapping file named salesorder.hbm.xml file which will map the class object with table, a configuration file hibernate.cfg.xml file that the hibernate utilizes for creating a pool connection and the required environment setup to work with database. Finally created a class where we will obtain the configuration, create a SessionFactory and obtain a session using SessionFactory, create a Transaction within which we will try to delete the existing data using delete query and updates using executeUpdate() method of Query. The value for deleting will be given by the user at run time.

Complete Code :

Example :

SalesOrder.java

package roseindia;

public class SalesOrder {
private int id;
private int price;
private String purchaser;

public SalesOrder()
{

}
public SalesOrder(int price, String purchaser)
{
this.price = price;
this.purchaser = purchaser;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getPurchaser() {
return purchaser;
}
public void setPurchaser(String purchaser) {
this.purchaser = purchaser;
}
}

salesorder.hbm.xml

<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia">
<class name="SalesOrder" table="salesorder">
<id name="id" type="int" column="id" >
</id>
<property name="price">
<column name="price" />
</property>
<property name="purchaser">
<column name="purchaser" />
</property>
</class>
</hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/data
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>

</hibernate-configuration>

HibernateDeleteQuery.java

package roseindia;

import java.util.Scanner;

import org.hibernate.Transaction;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateDeleteQuery {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String args[])
{
Session session = null;
try
{
try
{
Configuration cfg = new Configuration();
cfg.addResource("roseindia/salesorder.hbm.xml");
cfg.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch(Throwable th)
{
System.err.println("Failed to create sessionFactory object."
+ th);
throw new ExceptionInInitializerError(th);
}
session = sessionFactory.openSession();
Scanner scan = new Scanner(System.in);
Transaction t = session.beginTransaction();
System.out.println("Enter purchaser id to delete : ");
int id = scan.nextInt();
Query query = session.createQuery("delete SalesOrder so where so.id= '"+id+"'");
int update = query.executeUpdate();
if(update == 0 || update == 1)
{
System.out.println(update + " row affected");
}
else
System.out.println(update + " rows affected");

System.out.println("Records Deleted Successfully");
System.out.println("Successfully updated");
t.commit();
}
catch(Exception e) 
{
System.out.println(e.getMessage());
}
finally
{
session.close();
}
}
}

Output :

1. salesorder table before deleting the record

2. When you will execute the java file HibernateDeleteQuery.java (RightClick -> Run As -> Java Application) you will get the output as :

3. salesorder table after deleting the record

Download Source Code