Frameworks| Hibernate| Struts| JSF| JavaFX| Ajax| Spring| DOJO| JDO| iBatis| Questions? | Software Development
 

Hibernate Delete Query

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

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

                         

» View all related tutorials
Related Tags: java c database xml hibernate reflection com file ide class files orm table data development process form time object diff

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

22 comments so far (
post your own) View All Comments Latest 10 Comments:

Transaction.commit() is missig in the above example

Posted by Chandrasekhar on Thursday, 12.24.09 @ 11:34am | #93609

Guys,

If you are using the roseindia.tutorial.hibernate.Contact example - then the simple delete statement will not work. e.g
delete from contact where ID=3 - will give you a message like Contact is not mapped.

Correction is

String hql = "delete from roseindia.tutorial.hibernate.Contact where ID = 3";
will work fine.

Posted by Amit Kumar Ghosh on Thursday, 11.26.09 @ 14:32pm | #92868

Hello guys !
First I want to say that your tutorial is amazing and we can learn hibernate 3 very quickly ^_^

However the Query is not working here.With Eclipse it says "could not execute update query"..
Does anyone has the solution??
Thank you all

Posted by Rajesh Jayanathan on Monday, 11.23.09 @ 19:19pm | #92807

Need to add Transaction statement and use createSQLQuery() instead of createQuery() method.
-----------------------------
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DeleteHQLExample {

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 WHERE ID = 2";
Transaction tx = sess.beginTransaction();
Query query = sess.createSQLQuery(hql);
int row = query.executeUpdate();
tx.commit();
if(row == 0){
System.out.println(" Doesn't delete any row");
}else{
System.out.println(" Deleted row " + row);
}
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
sess.close();
}
}

}

Posted by Sudeepta Majhee on Saturday, 12.20.08 @ 09:09am | #82996

the example does not work. the following exception is thrown:

java.lang.NullPointerException
at org.hibernate.hql.antlr.HqlSqlBaseWalker.path(HqlSqlBaseWalker.java:2193)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:2281)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2232)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:498)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.deleteStatement(HqlSqlBaseWalker.java:276)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:156)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:189)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:130)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:83)
at org.hibernate.impl.SessionFactoryImpl.getQuery(SessionFactoryImpl.java:414)
at org.hibernate.impl.SessionImpl.getQueries(SessionImpl.java:814)
at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:801)
at org.hibernate.impl.QueryImpl.executeUpate(QueryImpl.java:89)
at roseindia.tutorial.hibernate.DeleteHQLExample.main(DeleteHQLExample.java:27)

Posted by kei on Thursday, 09.25.08 @ 05:47am | #80680

there is exception as follow:
java.lang.NullPointerException
at org.hibernate.hql.antlr.HqlSqlBaseWalker.path(HqlSqlBaseWalker.java:2193)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:2281)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2232)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:498)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.deleteStatement(HqlSqlBaseWalker.java:276)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:156)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:189)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:130)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:83)
at org.hibernate.impl.SessionFactoryImpl.getQuery(SessionFactoryImpl.java:414)
at org.hibernate.impl.SessionImpl.getQueries(SessionImpl.java:814)
at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:801)
at org.hibernate.impl.QueryImpl.executeUpate(QueryImpl.java:89)
at roseindia.tutorial.hibernate.DeleteHQLExample.main(DeleteHQLExample.java:27)

Posted by kei on Wednesday, 09.24.08 @ 22:20pm | #80673

I am new to Hibernate and this tutorial found it quite handy otherwise.

Posted by Anjana on Thursday, 08.14.08 @ 15:25pm | #72815

After googling a lot I found a better way to delete a record:
long contactid = 3;
Object contact = sess.load(Contact.class, contactid);
sess.delete(contact);

Posted by Anjana on Thursday, 08.14.08 @ 15:23pm | #72814

Hi
Actually above example is not woking. you have to modify code as follows

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
List insurance = session.createSQLQuery("select * from insurance ins where Id='2'").addEntity("ins", Insurance.class).list();
Insurance insuranceObject = null;
if(it.hasNext())
{
insuranceObject = (Insurance) it.next();
System.out.println("ID: " +
ct.getLngInsuranceId());
System.out.println("Name: " + insuranceObject.getInsuranceName());
}
session.delete(insuranceObject);
tx.commit();

Posted by pramod on Wednesday, 07.30.08 @ 16:44pm | #69975


If we write down the HQL in HQL editor(in MyEclips) how to transfer it in java class
Tanks 4 all and roseindia site

Posted by manjula on Wednesday, 05.14.08 @ 14:13pm | #59784

 
Tell A Friend
Your Friend Name

 

 
Recently Viewed
Software Solutions
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.