Hibernate operations (Data Deletion) - Part 4

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data retrieving through hibernate. (Data insertion article can be found at Part 1 of this series and data update article can be found at Part 2 of this article series)

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"


package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.
(This class is identical to the class that we used in part 1)


Data Deletion

Before writing codes for data deletion, you should have a knowledge about HQL for the hibernate. This HQL can be use to data retrieve,update and delete from db. If you do not have at least basis of the HQL please refer part 2 of this article series.


So, now let move to data deletion, this deletion is also a some kind of update to the db. Because deletion means removing specific field or fields from a table by changing its status (status means number of fields, file size, etc). Therefore the method that we used for update the db can be used for data deletion also. Here code for data deletion is not much differ from data updating.

Therefore the HQL query for data deletion is,

delete from Person

If we use this query itself for data deletion, the query will delete the current element from the table. But this thing won't be used for practical scenarios. Therefore we have to let it know 'what records to be deleted' by executing the query.

HQL query for data deletion with conditions

delete from Person as p where p.id = :key

Here I used the parameter(if you can remember) for this query named 'key'. (Need 'what is the parameter?' please refer part2 of this article series). Therefore the complete java code for this query is,


String searchId = "1";
String query = "
delete from Person as p where p.id = :key";

session.createQuery(query).setString("key",
searchId).executeUpdate();

Simply this is the way to update the database also, only change of this code is the word 'delete' in the query. Isn't it easy?...........But finally remember to commit the operation because 'we change the database's data'.

The complete java code for data deletion is,

package pkg;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

    public static void main(String[] args) {
       
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Person.class);
        config.configure("hibernate.cfg.xml");
       
        SessionFactory factory = config.buildSessionFactory();
             
        //beginning of the session
        Session session = factory.openSession();
        session.beginTransaction();//beginning of the transaction
       
       
String searchId = "1";//this is the key id for field being updated
       
        //create the delete query
       
String query = "delete from Person as p where p.id = :key";
       
       
session.createQuery(query).setString("key", searchId).executeUpdate();
        

        session.getTransaction().commit();//end of transaction
        session.close();//end of  session
       
       
        }

}

If you execute this code segment the field with id of  "1" will be deleted (if exist).
Also I have to mention here the method createQuery() will return the number of fields that it changed by executing the query. Therefore if you want to get the number of fields that changed or check whether any changes had been done by the query, you can use that number. To do that first assign the number return by method to the int variable.

int fieldCount = session.createQuery(query).setString("key", searchId).executeUpdate();

After that you can use this variable for get the number of fields that changed or check whether any changes had been done by the query.

For example,

int fieldCount = session.createQuery(query).setString("key", searchId).executeUpdate();

if(fieldCount > 0)
    System.out.printf("Number of fields changed %d\n", fieldCount);
else
    System.out.printf("No changes had been done\n");

Hmmmmm.... so this is the last article for hibernate operation article series. If you go through all the parts of this article series you will be able to do basic hibernate operations such as,
  • Data insertion.
  • Data updating
  • Data retrieving
  • Data deletion.


Related posts

No comments:

Post a Comment