HQL Insert,Update,Select and Delete Examples

Let us understand how to perform Insert,Update,Select and Delete operations in HQL

Example:

In this article,we will use Applicant and Applicant_Backup tables to perform all the above operations.

Applicant_Backup table will be used to store backup data from Applicant table using HQL Insert query.

Step 1

Create hibernate project

Please refer Hibernate setup in eclipse article on how to do it.

Project structure

HQLCRUDProjStructure

Step 2

Update pom.xml with Hibernate and Mysql dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.  
  5.   <groupId>HQLCRUDExamples</groupId>
  6.   <artifactId>HQLCRUDExamples</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <packaging>jar</packaging>
  9.  
  10.   <name>HQLCRUDExamples</name>
  11.   <url>http://maven.apache.org</url>
  12.  
  13.   <properties>
  14.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15.   </properties>
  16.  
  17.   <dependencies>
  18.     <dependency>
  19.       <groupId>junit</groupId>
  20.       <artifactId>junit</artifactId>
  21.       <version>3.8.1</version>
  22.       <scope>test</scope>
  23.     </dependency>
  24.      <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
  25.         <dependency>
  26.             <groupId>org.hibernate</groupId>
  27.             <artifactId>hibernate-core</artifactId>
  28.             <version>5.2.6.Final</version>
  29.         </dependency>
  30.         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  31.         <dependency>
  32.             <groupId>mysql</groupId>
  33.             <artifactId>mysql-connector-java</artifactId>
  34.             <version>6.0.5</version>
  35.         </dependency>
  36.   </dependencies>
  37. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>HQLCRUDExamples</groupId>
  <artifactId>HQLCRUDExamples</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>HQLCRUDExamples</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
  </dependencies>
</project>


We have added maven dependencies for Hibernate and MYSQL in this pom file.

Step 3

Create Applicant class

  1. package com.kb.model;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.Table;
  9.  
  10. @Entity
  11. @Table(name="Applicant")
  12. public class Applicant {
  13.     @Id
  14.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  15.     @Column(name = "Applicant_Id")
  16.     private int applicantId;
  17.    
  18.     @Column(name = "FirstName")
  19.     private String firstName;
  20.    
  21.     @Column(name = "LastName")
  22.     private String lastName;
  23.    
  24.     @Column(name = "Age")
  25.     private int age;
  26.    
  27.     @Column(name = "Education")
  28.     private String education;
  29.    
  30.    
  31.     public int getApplicantId() {
  32.         return applicantId;
  33.     }
  34.     public void setApplicantId(int applicantId) {
  35.         this.applicantId = applicantId;
  36.     }
  37.     public String getFirstName() {
  38.         return firstName;
  39.     }
  40.     public void setFirstName(String firstName) {
  41.         this.firstName = firstName;
  42.     }
  43.     public String getLastName() {
  44.         return lastName;
  45.     }
  46.     public void setLastName(String lastName) {
  47.         this.lastName = lastName;
  48.     }
  49.     public int getAge() {
  50.         return age;
  51.     }
  52.     public void setAge(int age) {
  53.         this.age = age;
  54.     }
  55.     public String getEducation() {
  56.         return education;
  57.     }
  58.     public void setEducation(String education) {
  59.         this.education = education;
  60.     }
  61. }
package com.kb.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Applicant")
public class Applicant {
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Applicant_Id")
	private int applicantId;
	
	@Column(name = "FirstName")
	private String firstName;
	
	@Column(name = "LastName")
	private String lastName;
	
	@Column(name = "Age")
	private int age;
	
	@Column(name = "Education")
	private String education;
	
	
	public int getApplicantId() {
		return applicantId;
	}
	public void setApplicantId(int applicantId) {
		this.applicantId = applicantId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getEducation() {
		return education;
	}
	public void setEducation(String education) {
		this.education = education;
	}
}


We have specified Primary key as applicantId and generator class as “sequence” for automatic primary key generation.

Step 4

Create ApplicantBackup class

  1. package com.kb.model;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.Table;
  9.  
  10. @Entity
  11. @Table(name="Applicant_Backup")
  12. public class ApplicantBackup {
  13.  
  14.     @Id
  15.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  16.     @Column(name = "Applicant_Backup_Id")
  17.     private int applicantId;
  18.    
  19.     @Column(name = "FirstName")
  20.     private String firstName;
  21.    
  22.     @Column(name = "LastName")
  23.     private String lastName;
  24.    
  25.     @Column(name = "Age")
  26.     private int age;
  27.    
  28.     @Column(name = "Education")
  29.     private String education;
  30.    
  31.    
  32.     public int getApplicantId() {
  33.         return applicantId;
  34.     }
  35.     public void setApplicantId(int applicantId) {
  36.         this.applicantId = applicantId;
  37.     }
  38.     public String getFirstName() {
  39.         return firstName;
  40.     }
  41.     public void setFirstName(String firstName) {
  42.         this.firstName = firstName;
  43.     }
  44.     public String getLastName() {
  45.         return lastName;
  46.     }
  47.     public void setLastName(String lastName) {
  48.         this.lastName = lastName;
  49.     }
  50.     public int getAge() {
  51.         return age;
  52.     }
  53.     public void setAge(int age) {
  54.         this.age = age;
  55.     }
  56.     public String getEducation() {
  57.         return education;
  58.     }
  59.     public void setEducation(String education) {
  60.         this.education = education;
  61.     }
  62. }
package com.kb.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Applicant_Backup")
public class ApplicantBackup {

	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Applicant_Backup_Id")
	private int applicantId;
	
	@Column(name = "FirstName")
	private String firstName;
	
	@Column(name = "LastName")
	private String lastName;
	
	@Column(name = "Age")
	private int age;
	
	@Column(name = "Education")
	private String education;
	
	
	public int getApplicantId() {
		return applicantId;
	}
	public void setApplicantId(int applicantId) {
		this.applicantId = applicantId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getEducation() {
		return education;
	}
	public void setEducation(String education) {
		this.education = education;
	}
}


We have specified Primary key as applicantId and generator class as “sequence” for automatic primary key generation.
Applicant_Backup table will be used to store backup data from Applicant table using HQL Insert query.

Step 5

Create hibernate.cfg.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8.    <session-factory>
  9.  
  10.        <!-- Database connection properties -->
  11.        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  12.        <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
  13.        <property name="connection.username">root</property>
  14.        <property name="connection.password">root</property>
  15.  
  16.        <!-- JDBC connection pool (using the built-in) -->
  17.        <property name="connection.pool_size">100</property>
  18.  
  19.        <!-- SQL dialect -->
  20.        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  21.  
  22.        <!-- Disable the second-level cache -->
  23.        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
  24.  
  25.        <!-- Echo all executed SQL to stdout -->
  26.        <property name="show_sql">true</property>
  27.        
  28.        <!-- Format the generated Sql -->
  29.        <property name="format_sql">true</property>
  30.  
  31.        <!-- Dont Drop and re-create the database schema on startup,Just update it -->
  32.        <property name="hbm2ddl.auto">update</property>
  33.  
  34.           <mapping class="com.kb.model.Applicant" />
  35.       <mapping class="com.kb.model.ApplicantBackup" />
  36.  
  37.    </session-factory>
  38.  
  39. </hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
   <session-factory>
 
       <!-- Database connection properties -->
       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
       <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
       <property name="connection.username">root</property>
       <property name="connection.password">root</property>
 
       <!-- JDBC connection pool (using the built-in) -->
       <property name="connection.pool_size">100</property>
 
       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
       <!-- Disable the second-level cache -->
       <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
 
       <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">true</property>
       
       <!-- Format the generated Sql -->
       <property name="format_sql">true</property>
 
       <!-- Dont Drop and re-create the database schema on startup,Just update it -->
       <property name="hbm2ddl.auto">update</property>
 
          <mapping class="com.kb.model.Applicant" />
	  <mapping class="com.kb.model.ApplicantBackup" />
 
   </session-factory>
 
</hibernate-configuration>


We have defined all the database configuration in this file

hbm2ddl.auto property is defined in the config file which helps in automatic creation of tables in the database based on the mapping.

We have also provided the mapping class names using “mapping” tag.

Step 6

Create Hibernate util class

  1. package com.kb.util;
  2.  
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5.  
  6. public class HibernateUtil {
  7.     private static final SessionFactory sessionFactory = buildSessionFactory();
  8.  
  9.     private static SessionFactory buildSessionFactory() {
  10.         try {
  11.             // Create the SessionFactory from hibernate.cfg.xml
  12.             return new Configuration().configure().buildSessionFactory();
  13.         } catch (Throwable ex) {
  14.             // Make sure you log the exception to track it
  15.             System.err.println("SessionFactory creation failed." + ex);
  16.             throw new ExceptionInInitializerError(ex);
  17.         }
  18.     }
  19.  
  20.     public static SessionFactory getSessionFactory() {
  21.         return sessionFactory;
  22.     }
  23.    
  24.     public static void shutdown() {
  25.         // Optional but can be used to Close caches and connection pools
  26.         getSessionFactory().close();
  27.     }
  28.  
  29. }
package com.kb.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception to track it
            System.err.println("SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void shutdown() {
    	// Optional but can be used to Close caches and connection pools
    	getSessionFactory().close();
    }

}

Step 7

Create PopulateData.java file to Populate Tables with initial data

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6.  
  7. import com.kb.model.Applicant;
  8. import com.kb.util.HibernateUtil;
  9.  
  10. public class PopulateData {
  11. public static void main(String[] args) {
  12.  
  13.     // Get session factory using Hibernate Util class
  14.     SessionFactory sf = HibernateUtil.getSessionFactory();
  15.     // Get session from Sesson factory
  16.     Session session = sf.openSession();
  17.  
  18.     // Begin transaction
  19.     Transaction t = session.beginTransaction();
  20.    
  21.     //Create Applicant Model data
  22.     Applicant applicant1 = new Applicant();
  23.     applicant1.setFirstName("John");
  24.     applicant1.setLastName("KC");
  25.     applicant1.setAge(28);
  26.     applicant1.setEducation("Graduation");
  27.    
  28.     Applicant applicant2 = new Applicant();
  29.     applicant2.setFirstName("Jacob");
  30.     applicant2.setLastName("JC");
  31.     applicant2.setAge(30);
  32.     applicant2.setEducation("Graduation");
  33.  
  34.    
  35.     session.save(applicant1);
  36.     session.save(applicant2);
  37.  
  38.     // Commit the transaction and close the session
  39.     t.commit();
  40.    
  41.     session.close();
  42.     System.out.println("successfully persisted Applicant details");
  43.  
  44.     }
  45.  
  46. }
package com.kb.db;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.kb.model.Applicant;
import com.kb.util.HibernateUtil;

public class PopulateData {
public static void main(String[] args) {

	// Get session factory using Hibernate Util class
	SessionFactory sf = HibernateUtil.getSessionFactory();
	// Get session from Sesson factory
	Session session = sf.openSession();

	// Begin transaction
	Transaction t = session.beginTransaction();
	
	//Create Applicant Model data
	Applicant applicant1 = new Applicant();
	applicant1.setFirstName("John");
	applicant1.setLastName("KC");
	applicant1.setAge(28);
	applicant1.setEducation("Graduation");
	
	Applicant applicant2 = new Applicant();
	applicant2.setFirstName("Jacob");
	applicant2.setLastName("JC");
	applicant2.setAge(30);
	applicant2.setEducation("Graduation");

	
	session.save(applicant1);
	session.save(applicant2);

	// Commit the transaction and close the session
	t.commit();
	
	session.close();
	System.out.println("successfully persisted Applicant details");

    }

}


In this class, we are persisting 2 Applicant details which will be used to perform all the CRUD operations.

Lets create separate classes to perform various HQL CRUD operations

Step 8

Create SelectQuery.java

  1. package com.kb.db;
  2.  
  3. import java.util.List;
  4.  
  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.hibernate.query.Query;
  8.  
  9. import com.kb.model.Applicant;
  10. import com.kb.util.HibernateUtil;
  11.  
  12. public class SelectQuery {
  13.     public static void main(String[] args) {
  14.         // Get session factory using Hibernate Util class
  15.         SessionFactory sf = HibernateUtil.getSessionFactory();
  16.         // Get session from Sesson factory
  17.         Session session = sf.openSession();
  18.         @SuppressWarnings("rawtypes")
  19.         Query query = session.createQuery("from Applicant");
  20.         List<Applicant> list = query.getResultList();
  21.         System.out.println("Number of Applicants present--> "+list.size());
  22.         for (Applicant applicant : list) {
  23.            
  24.             System.out.println(applicant.getApplicantId());
  25.             System.out.println(applicant.getFirstName());
  26.         }
  27.        
  28.         session.close();
  29.     }
  30.  
  31. }
package com.kb.db;

import java.util.List;

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

import com.kb.model.Applicant;
import com.kb.util.HibernateUtil;

public class SelectQuery {
	public static void main(String[] args) {
		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Sesson factory
		Session session = sf.openSession();
		@SuppressWarnings("rawtypes")
		Query query = session.createQuery("from Applicant");
		List<Applicant> list = query.getResultList();
		System.out.println("Number of Applicants present--> "+list.size());
		for (Applicant applicant : list) {
			
			System.out.println(applicant.getApplicantId());
			System.out.println(applicant.getFirstName());
		}
		
		session.close();
	}

}

Step 9

Create UpdateQuery.java

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6. import org.hibernate.query.Query;
  7.  
  8. import com.kb.util.HibernateUtil;
  9.  
  10. public class UpdateQuery {
  11.  
  12.     public static void main(String[] args) {
  13.         // Get session factory using Hibernate Util class
  14.         SessionFactory sf = HibernateUtil.getSessionFactory();
  15.         // Get session from Sesson factory
  16.         Session session = sf.openSession();
  17.         Query query = session.createQuery("update Applicant set age=:age where id=:id");
  18.         query.setParameter("age", 30);
  19.         query.setParameter("id", 1);
  20.         // Begin transaction
  21.         Transaction t = session.beginTransaction();
  22.         int result = query.executeUpdate();
  23.         // Commit the transaction and close the session
  24.         t.commit();
  25.         System.out.println("No of rows updated: "+result);
  26.        
  27.         session.close();
  28.     }
  29.  
  30.  
  31.  
  32. }
package com.kb.db;

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

import com.kb.util.HibernateUtil;

public class UpdateQuery {

	public static void main(String[] args) {
		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Sesson factory
		Session session = sf.openSession();
		Query query = session.createQuery("update Applicant set age=:age where id=:id");
		query.setParameter("age", 30);
		query.setParameter("id", 1);
		// Begin transaction
		Transaction t = session.beginTransaction();
		int result = query.executeUpdate();
		// Commit the transaction and close the session
		t.commit();
		System.out.println("No of rows updated: "+result);
		
		session.close();
	}



}

Step 10

Create InsertQuery.java

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6. import org.hibernate.query.Query;
  7.  
  8. import com.kb.util.HibernateUtil;
  9.  
  10. public class InsertQuery {
  11.  
  12.     public static void main(String[] args) {
  13.         // Get session factory using Hibernate Util class
  14.         SessionFactory sf = HibernateUtil.getSessionFactory();
  15.         // Get session from Sesson factory
  16.         Session session = sf.openSession();
  17.         Query query = session.createQuery("insert into ApplicantBackup (applicantId,
  18.                                                         firstName,lastName,age,education)
  19.                                                     select id, firstName,lastName,age,education from Applicant");
  20.         // Begin transaction
  21.         Transaction t = session.beginTransaction();
  22.         int result = query.executeUpdate();
  23.         // Commit the transaction and close the session
  24.         t.commit();
  25.         System.out.println("No of rows inserted: "+result);
  26.        
  27.         session.close();
  28.     }
  29.  
  30. }
package com.kb.db;

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

import com.kb.util.HibernateUtil;

public class InsertQuery {

	public static void main(String[] args) {
		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Sesson factory
		Session session = sf.openSession();
		Query query = session.createQuery("insert into ApplicantBackup (applicantId, 
                                                         firstName,lastName,age,education) 
                                                     select id, firstName,lastName,age,education from Applicant");
		// Begin transaction
		Transaction t = session.beginTransaction();
		int result = query.executeUpdate();
		// Commit the transaction and close the session
		t.commit();
		System.out.println("No of rows inserted: "+result);
		
		session.close();
	}

}

Step 11

Create DeleteQuery.java

  1. package com.kb.db;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6. import org.hibernate.query.Query;
  7.  
  8. import com.kb.util.HibernateUtil;
  9.  
  10. public class DeleteQuery {
  11.  
  12.     public static void main(String[] args) {
  13.         // Get session factory using Hibernate Util class
  14.         SessionFactory sf = HibernateUtil.getSessionFactory();
  15.         // Get session from Sesson factory
  16.         Session session = sf.openSession();
  17.         Query query = session.createQuery("delete from ApplicantBackup where id=:id");
  18.         query.setParameter("id", 1);
  19.         // Begin transaction
  20.         Transaction t = session.beginTransaction();
  21.         int result = query.executeUpdate();
  22.         // Commit the transaction and close the session
  23.         t.commit();
  24.         System.out.println("No of rows Deleted: "+result);
  25.        
  26.         session.close();
  27.     }
  28.  
  29. }
package com.kb.db;

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

import com.kb.util.HibernateUtil;

public class DeleteQuery {

	public static void main(String[] args) {
		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Sesson factory
		Session session = sf.openSession();
		Query query = session.createQuery("delete from ApplicantBackup where id=:id");
		query.setParameter("id", 1);
		// Begin transaction
		Transaction t = session.beginTransaction();
		int result = query.executeUpdate();
		// Commit the transaction and close the session
		t.commit();
		System.out.println("No of rows Deleted: "+result);
		
		session.close();
	}

}

Step 12

Lets execute each of these operations one by one and check the output in MYSQL using below steps

E:\MySql_Install\bin
Mysql –u root –p
Enter password

Use javainsimpleway;

Run PopulateData.java class to create the initial data

Select * from Applicant;

Select * from Applicant_Backup;

populateDataOutput

We can see that Applicant table has 2 records and Applicant_Backup table is empty.


Run SelectQuery.java class to get the data from db

Output


Run UpdateQuery.java class to update the age of an Applicant to 30 whose ID is 1

Output

Check an updated row in DB

Select * from Applicant;

UpdateDataOutput

We can see that Applicant table has got the Age updated for an Applicant whose ID is 1.


Run InsertQuery.java class to insert the Applicant details to ApplicantBackup

Output

Check an inserted data in DB

Select * from Applicant;

Select * from Applicant_Backup;

InsertDataOutput

We can see that Applicant_Backup table has got all the records from Applicant table.


Run DeleteQuery.java class to delete the Applicant whose ID is 1

Output

Check data is deleted in DB for confirmation

Select * from Applicant_Backup;

DeleteDataOutput

We can see that Applicant_Backup table is now left with only 1 record due to deletion of 1 record.

Download this project HQLCRUDExamples

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on