Followers

hb : deleting the single record using hibernate

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="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/hari</property>
    <property name="hibernate.connection.username">app</property>
    <property name="hibernate.connection.password">app</property>
    <property name="show_sql">false</property>
    <property name="hbm2ddl.auto">create</property> 
    <mapping resource="Employee.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


Employee.java
==============

package mypack;

public class Employee {
    private int id;
    private String firstName;
    private String lastName;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}


Employee.hbm.xml
=================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="mypack.Employee" table="MYEMP" >
        <id name="id">

        </id>
        <property name="firstName" ></property>
        <property name="lastName" ></property>        
    </class>
</hibernate-mapping>

DeleteQueryEx.java
=====================

package mypack;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DeleteQueryEx {

    public static void main(String[] args) {

         //creating configuration object  
    Configuration cfg=new Configuration();  
    cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
    //creating seession factory object  
    SessionFactory factory=cfg.buildSessionFactory();  
      
    //creating session object  
    Session session=factory.openSession();  
    Employee emp = (Employee)session.load(Employee.class, 333);
    System.out.println(emp.getId()+" "+emp.getFirstName()+" "+emp.getLastName());
        Transaction tx = session.beginTransaction();
        session.delete(emp);
        tx.commit();        
    session.close();  
    System.out.println("successfully retrieved record");  
    }
}

No comments:

Post a Comment