Choose Your Language

Wednesday 18 November 2015

Hibernate crud operations

Project Structure



Create database with name retailer

CREATE database retailer;

USE retailer;

CREATE TABLE  `retailer`.`customers` (
  `name` varchar(20) DEFAULT NULL,
  `C_ID` int(11) NOT NULL AUTO_INCREMENT,
  `address` varchar(20) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`C_ID`)
) ;

customersmapping.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="hibernatetest.Customer" table="customers">      
  <id column="C_ID" name="customerID" type="int">
  <generator class="native"></generator>
  </id>  
  <property name="customerName">
  <column name="name"></column>
  </property>  
  <property name="customerAddress">
  <column name="address"></column>
  </property>  
  <property name="customerEmail">
  <column name="email"></column>
  </property>  
  </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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/retailer</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="current_session_context_class">thread</property>
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <property name="show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping resource="customersmapping.hbm.xml"/>  
  </session-factory>
</hibernate-configuration>

Customer .java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernatetest;

/**
 *
 * @Aravind Sankaran Nair
 */
public class Customer {
    private String customerName;
    private int customerID;
    private String customerAddress;
    private String customerEmail;

    public void setCustomerAddress(String customerAddress) {
        this.customerAddress = customerAddress;
    }

    public void setCustomerEmail(String customerEmail) {
        this.customerEmail = customerEmail;
    }

    public void setCustomerID(int customerID) {
        this.customerID = customerID;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCustomerAddress() {
        return customerAddress;
    }

    public String getCustomerEmail() {
        return customerEmail;
    }

    public int getCustomerID() {
        return customerID;
    }

    public String getCustomerName() {
        return customerName;
    }    
 
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernatetest;

import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Aravind Sankaran Nair
 */
public class HibernateCrud {
    Session session = null;
    SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();     
    void insertData(){
        try{
        session =sessionFactory.openSession();
        session.beginTransaction();                
        Customer customer = new Customer();
        customer.setCustomerName("Aravind");
        customer.setCustomerAddress("Trivandrum,India");
        customer.setCustomerEmail("aravind@gmail.com");  
        session.save(customer);           
        session.getTransaction().commit();       
        }
     
    catch(Exception e){
        System.out.println(e.getMessage());
    }
  
  finally{
    session.flush();
    session.close();
  } 
}
    void updateData(){         
    try{        
        session =sessionFactory.openSession();
        session.beginTransaction();    
        String HQL_QUERY ="from Customer customers where customers.customerID = :customerId";
        org.hibernate.Query query = session.createQuery(HQL_QUERY);
        int C_ID=10;
        query.setParameter("customerId",C_ID);
        System.out.println("Reading values");
         for(Iterator it=query.iterate();it.hasNext();){
             Customer customer = (Customer) it.next();            
             customer.setCustomerName("updated data");
             customer.setCustomerAddress("updated data");
             customer.setCustomerEmail("updated data");
             session.update(customer);             
            }
       session.getTransaction().commit();
      
        }
     
    catch(Exception e){
        System.out.println(e.getMessage());
    }
  
  finally{
    session.flush();
    session.close();
  }
}
    void retriveData(){
        try{        
        session =sessionFactory.openSession();
        session.beginTransaction();
    
        String HQL_QUERY ="from Customer customers where customers.customerID = :customerId";
        org.hibernate.Query query = session.createQuery(HQL_QUERY);
       int C_ID=10
        query.setParameter("customerId",C_ID);
       
         for(Iterator it=query.iterate();it.hasNext();){
             Customer customer = (Customer) it.next();
             System.out.println(customer.getCustomerName());
             System.out.println(customer.getCustomerAddress());
             System.out.println(customer.getCustomerEmail());
             System.out.println(customer.getCustomerID());        
            }
        session.getTransaction().commit();
       
        }
     
    catch(Exception e){
        System.out.println(e.getMessage());
    }
  
  finally{
    session.flush();
    session.close();
  }
}
    
   
    void deleteData(){
        try{
        
        session =sessionFactory.openSession();
        session.beginTransaction();
    
        String HQL_QUERY ="from Customer customers where customers.customerID = :customerId";
        org.hibernate.Query query = session.createQuery(HQL_QUERY);  
        int C_ID=10      
        query.setParameter("customerId",C_ID);
       
         for(Iterator it=query.iterate();it.hasNext();){
             Customer customer = (Customer) it.next();            
             customer.setCustomerName("update");
             customer.setCustomerAddress("update");
             customer.setCustomerEmail("update");
             session.delete(customer);
            }
       session.getTransaction().commit();
        
        }
     
    catch(Exception e){
        System.out.println(e.getMessage());
    }
  
  finally{
    session.flush();
    session.close();
  }
    }
    public static void main(String[] args) {
       HibernateCrud hc=new HibernateCrud();
       hc.insertData();
       hc.updateData();
       hc.retriveData();
       hc.deleteData();
 }
}

Jar File Needed:

derbyclient.jar

No comments:

Post a Comment