Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials
  

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
Hibernate
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

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

                         

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

Current Comments

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

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

this tut is good...keep it up

Posted by aditya on Friday, 05.9.08 @ 13:23pm | #59007

hibernate3 jar interface Query is having method 'executeUpate' and in example we are using 'executeUpdate'. And while executing Delete process I am getting exception

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
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:23)
null

Can you please help me in this error.

Posted by Abhi on Thursday, 05.8.08 @ 12:15pm | #58891

A lots thanks to Roseindia for this tutorial, but on execution I've:
NULL

and no change in my database.


Then I've addded the "Transaction instructions" and I've changed the "hql" String in:

delete Insurance where id = 2

and on execution I've:

Hibernate: delete from INSURANCE insurance0_ where (id=2)
Exception in thread "main"
org.hibernate.exception.SQLGrammarException: could not execute update query
....
Caused by: java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insurance0_ where (id=2)' at line 1"

Where i wrong?

Posted by magister on Thursday, 04.17.08 @ 14:35pm | #56788

this example doesn't work properly..you must use transaction..

Transaction tx = sess.beginTransaction();
tx.commit();

Posted by Magicman on Friday, 03.21.08 @ 14:14pm | #53569

HIbernate tutorial for validating a jsp form

Posted by rajesh on Wednesday, 02.20.08 @ 15:59pm | #49202

A lots thanks to Roseindia for the beginner tutorial on hibernate & swing...
Dayal

Posted by Dayal Manna on Monday, 02.18.08 @ 17:29pm | #48892

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

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.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

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

Indian Software Development Company

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

Copyright © 2007. All rights reserved.