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 for this: 

here we give the code of java class HibernateTestDemo.java which we will delete a row from the USER_TABLE table using the query      “delete from USER_TABLE where USER_ID = 2”

Following is USER_TABLE: 

package com.sdnext.hibernate.tutorial;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.sdnext.hibernate.tutorial.dto.UserDetails;

public class HibernateTestDemo {
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        String sql = “DELETE FROM UserDetails WHERE USER_ID = 2”;
        Query query = session.createQuery(sql);
         int row = query.executeUpdate();
         if (row == 0)
             System.out.println(“Doesnt deleted any row!”);
         else
             System.out.println(“Deleted Row: ” + row);
        session.getTransaction().commit();
        session.close();
    }
}

Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: delete from USER_TABLE where USER_ID=2
Deleted Row: 1

Now we look the following table structure—

Now in the Next Chapter we will see how to work on Value Types and Embedding Objects.

                                <<Previous Chapter 11<<    >>Next Chapter13


View Comments