A CRUD operation deals with creating , retriving , updating and deleting from the table, in this tutorial we will see how it is done.,


We have already described previously how to persist "Employee" Class to database. Here we are adding more operation on that
Employee Class.
1 Persisting the class to databae
2 Retriving records from database
3 Deleting decord (condition: where deptno is 30)
4 Updating decord(Condition : Where sal is 8000 ,update sal to 11000)


Steps are  almost same as before we have discussed


Step1: Create  Employee Pojo class

package com.bullraider.crud;
import java.io.Serializable;
public class Employee implements Serializable{
    private long empno;
    private String ename;
    private int sal;
    private String job;
    private int deptno ;
    public long getEmpno() {
        return empno;
    }
     public void setEmpno(long empno) {
        this.empno = empno;
    }
      public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public int getSal() {
        return sal;
    }
    public void setSal(int sal) {
        this.sal = sal;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public int getDeptno() {
        return deptno;
    }
    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }
}

Step2: Create Employee.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="com.bullraider.crud.Employee" table="emp1000">
  <meta attribute="class-description"> This class contains employee details. </meta>
  <id name="empno" type="long" column="empno">
   <generator class="native" />
  </id>
  <property name="ename" type="string" column="ename" not-null="true" />
  <property name="job" type="string" column="job" not-null="true" />
  <property name="sal" type="integer" column="sal" not-null="true" />
  <property name="deptno" type="integer" column="deptno"
   not-null="true" />
 </class>
</hibernate-mapping>


Step3: Create Configuration file i.e 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">oracle.jdbc.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property>
        <property name="hibernate.connection.username">scott</property>
        <property name="connection.password">tiger</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="show_sql">true</property>
       <property name="hbm2ddl.auto">create-drop</property>
        <mapping resource="com/bullraider/crud/Employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Step4: Create HibernateUtil class to get SessionFactory Object

package com.bullraider.crud.util;

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

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("SessionFactory creation failed" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

 

Step5: Create One Main Class for adding opertions.

package com.bullraider.crud;
import java.util.Iterator;
import java.util.List;
import com.bullraider.crud.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Main {
    public static void main(String[] args) {
        Main m=new Main();
        m.saveEmployee("Rex", "MGR", 30000, 10);
        m.saveEmployee("Raj", "CLERK", 10000, 30);
        m.saveEmployee("Mike", "SALESMAN", 8000, 10);
        m.retriveEmployee();
        m.deleteEmployee();
        m.updateEmployee();
    }
    public void saveEmployee(String ename,String job,int sal,int deptno){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Employee emp=new Employee();
            emp.setEname(ename);
            emp.setJob(job);
            emp.setSal(sal);
            emp.setDeptno(deptno);
            session.save(emp);
            transaction.commit();
            System.out.println("Records inserted sucessessfully");
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    public void retriveEmployee()
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
                        List employee = session.createQuery("from Employee").list();
            for (Iterator iterator = employee.iterator(); iterator.hasNext();)
            {
                Employee employee1 = (Employee) iterator.next();
                System.out.println(employee1.getEmpno()+"  "+employee1.getEname()+"  "+ employee1.getJob()+"   "+employee1.getSal()+"   "+employee1.getDeptno());
            }          
            transaction.commit();
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    public  void  deleteEmployee(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            String queryString = "from Employee where deptno = :deptno";
            Query query = session.createQuery(queryString);
            query.setInteger("deptno", 30);
            Employee employee=(Employee) query.uniqueResult();
            session.delete(employee);
            System.out.println("One employee is deleted!");
       
              //Another way to write it
            /*
             * String hql = "delete from Employee insurance where deptno = 30";
              Query query1 = session.createQuery(hql);
              int row = query1.executeUpdate();
              if (row == 0){
              System.out.println("Doesn't deleted any row!");
              }
              else{
              System.out.println("Deleted Row: " + row);
              }*/
        System.out.println("One employee is deleted!");
        } catch (HibernateException e) {
            transaction .rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
    public  void  updateEmployee(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            String queryString = "from Employee where sal = :sal";
            Query query = session.createQuery(queryString);
            query.setInteger("sal", 8000);
            Employee employee=(Employee) query.uniqueResult();
            employee.setSal(11000);
            session.update(employee);
            System.out.println("One employee is updated!");
        } catch (HibernateException e) {
            transaction .rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}


Download crud_in_hibernate.zip