Newsletter

Example On Hibernate Delete Query

Hibernate » on Jun 12, 2011 { 10 Comments } By Sivateja

This is the program to Delete a row (Object) from the database, just like using delete query in the jdbc program..

Files required to execute this program..

  • Product.java (My POJO class)
  • Product.hbm.xml (Xml mapping file )
  • hibernate.cfg.xml (Xml configuration file)
  • ClientProgram.java(java file to write our hibernate logic)

Product.java (POJO)

package str;

public class Product{

	private int productId;
	private String proName;
	private double price;

	public void setProductId(int productId)
	{
	    this.productId = productId;
	}
	public int getProductId()
	{
	    return productId;
	}

	public void setProName(String proName)
	{
	    this.proName = proName;
	}
	public String getProName()
	{
	    return proName;
	}

	public void setPrice(double price)
	{
	    this.price = price;
	}
	public double getPrice()
	{
	    return price;
	}
}

 

Product.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="str.Product" table="products">

<id name="productId" column="pid"  />
<property name="proName" column="pname" length="10"/>
<property name="price"/>

</class>
</hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping resource="Product.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

ClientProgram.java

package str;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class ClientProgram { 

    public static void main(String[] args)
    {

        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml"); 

        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();

        Object o=session.load(Product.class,new Integer(103));
        Product p=(Product)o;

        Transaction tx = session.beginTransaction();
        session.delete(p);
        System.out.println("Object Deleted successfully.....!!");
        tx.commit();
        session.close();
        factory.close();
    }

}

 

As usual compile all .java programs and run ClientProgram.java to see the output

Eclipse output

Oracle DB, Before Run The Program

Oracle DB, After Run the program

Note:

  • To deleting the object( 1 row) form the database we need to call delete method in the session.
  • In the hibernate we have only one method to delete an object from the database that is what i have shown you here..

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

10 Responses to “Example On Hibernate Delete Query”
  1. manik says:

    Hello,
    are the column names in the pojo class case sensitive??

  2. bbvnb says:

    its very gud website to leran basic concepts

  3. Nagaraju says:

    Hi Siva,

    Can we delete multiple rows at a time,
    for eg i am using the below code to delete multiple rows

    Object o=session.load(Sample.class,new Integer(9035));
    Object o1=session.load(Sample.class,new Integer(9037));
    Sample s=(Sample)o;
    Sample s1=(Sample)o1;
    Transaction tx = session.beginTransaction();
    session.delete(s);
    session.delete(s1);

    but is it possible to write the above code in oneline like

    Object o1=session.load(Sample.class,new Integer(9037,9035));

    Please give me the clarification for this post.

    Thanks…..

    • Manisha says:

      Object o1=session.load(Sample.class,new Integer(9037,9035));
      if you write this, it gives an Error like "Remove argument to match Integer(int);"

      we can delete multiple data like this…….
      Object o=session.load(Sample.class,new Integer(9035));
      Object o1=session.load(Sample.class,new Integer(9037));
      Sample s=(Sample)o;
      Sample s1=(Sample)o1;
      Transaction tx = session.beginTransaction();
      session.delete(s);
      session.delete(s1);

  4. Pallavi HN says:

    Sir, in hibernate we are having delete(String agr0,Object obj).what is the use of this.can you expalin us please.Thank you

  5. Avinash Kumar says:

    Yes, We can delete multiple rows at a time.

  6. santhosh says:

    Hello siva,
    Iam unable to delete the rows from my table.do we create table already in our database before deleted.

    And why the ddl is update while we perform delete query.

    please help me in doing this.

    Thanks in advance.

  7. Sanjay says:

    You are sending product id 103 like
    Object o=session.load(Product.class,new Integer(103));

    How hibernate will identify we are sending product id???

  8. Nadeem says:

    Hi I am getting this exception. Please help me:

    Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:264)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:228)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:727)
    at str.ClientForSave.main(ClientForSave.java:14)
    Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:101)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections.addConnections(PooledConnections.java:106)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:40)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:19)
    at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:138)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:110)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:74)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254)
    … 14 more
    Caused by: com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

    ** BEGIN NESTED EXCEPTION **

    java.net.SocketException
    MESSAGE: java.net.ConnectException: Connection refused: connect

    STACKTRACE:

    java.net.SocketException: java.net.ConnectException: Connection refused: connect

  9. tukaram mane says:

    Hi sir, I want to upload image in folder using hibernate, please help me!

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.