Saturday, January 5, 2013

Hibernate : CRUD Operations on the objects

Here I have demonstrated the basic CRUD operation using Hibernate API

To add records to the database, all you need to do it create an instance of your Model Class, create an instance of the Hibernate SessionFactory, grab an actual Hibernate Session from that factory start a transaction, pass your POJO instance to the save method of the Session, and then commit the transaction.

we can use the get method of the Hibernate Session to pull that instance out of the database, simply by passing in the class type and the primary key as arguments:

The get method of the Hibernate Session will return one entity. If you need to return multiple entities, you create a Hibernate query. you can use a Hibernate query to grab every record in the database as a list.

To delete a record, simply obtain the record from Hibernate using the get method and then pass the obtained object to the delete method of the Hibernate Session, all within an active transaction.

Here is the complete code to obtain all this in same place.

Create your project structure as shown in figure and add the hibernate related configuration to the project if you are not familier with hibernate configuration then fallow this link : Configuration and setting of Hibernate




















Configure hibernate.cfg.xml as fallows
<?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>

<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/deptt</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>


<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>


<!-- Disable the second-level cache  -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<mapping class="com.rajkrrsinghblogspot.model.Employee"/>

</session-factory>

</hibernate-configuration>



Create your Model class and annotate it with javax.persistance annotation
package com.rajkrrsinghblogspot.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="EMPLOYEE")
public class Employee {

@Id @GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="EMPID")
private int empId;

@Column(name="EMP_NAME")
private String empName;

@Column(name="DESIGNATION")
private String designation;

public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}



}


Create HibernateUtil class to expose the SessionFactory when required instead of recreate every time.
package com.rajkrrsinghblogspot.sessionfactory;

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

public class HibernateUtilImpl  {

private static SessionFactory sessionFactory;

public static  SessionFactory getSessionFacotry(){
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
}catch(HibernateException he){
he.printStackTrace();
}
return sessionFactory;
}

}


Now Create your Main class to test out all the operation.
package com.rajkrrsinghblogspot.main;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.rajkrrsinghblogspot.model.Employee;
import com.rajkrrsinghblogspot.sessionfactory.HibernateUtilImpl;

public class MainClass {

public static void main(String[] args) {
//createEmployee();
//readEmployee();
//updateEmployee();
deleteEmployee();
}


private static void createEmployee() {
Employee emp = new Employee();
emp.setEmpName("Amit Singh");
emp.setDesignation("Managar");

Employee empp = new Employee();
empp.setEmpName("Vijay Singh");
empp.setDesignation("TL");

SessionFactory sf = HibernateUtilImpl.getSessionFacotry();
Session session = sf.openSession();
session.beginTransaction();
session.save(emp);
session.save(empp);
session.getTransaction().commit();
session.close();

}


private static void readEmployee() {
Employee emp1 = new Employee();

SessionFactory sf = HibernateUtilImpl.getSessionFacotry();
Session session = sf.openSession();
session.beginTransaction();

// provided primary key to get the perticular record
emp1 = (Employee) session.get(Employee.class, 1);
System.out.println("The name of employee is "+emp1.getEmpName()+" And the designation of Emp is "
+emp1.getDesignation());
session.getTransaction().commit();
session.close();

// to selector list all the record in the table using HQL
session = sf.openSession();
session.beginTransaction();
Query query = session.createQuery("from Employee");
List<Employee> list = query.list();
System.out.println("\n");
System.out.println("::::::::::Printing Emp Details:::::::::::");
System.out.println("\n");
for(Employee emp : list){
System.out.println("Emp id is "+emp.getEmpId()+" Emp Name is "+emp.getEmpName()
+" and the designation is "+emp.getDesignation());
}
session.getTransaction().commit();
session.close();

}

private static void updateEmployee() {
Employee emp1 = new Employee();

SessionFactory sf = HibernateUtilImpl.getSessionFacotry();
Session session = sf.openSession();
session.beginTransaction();

// provided primary key to get the perticular record
emp1 = (Employee) session.get(Employee.class, 1);
emp1.setDesignation("SSE");
System.out.println("Designation updated successfully");
session.getTransaction().commit();
session.close();

}
private static void deleteEmployee() {
SessionFactory sf = HibernateUtilImpl.getSessionFacotry();
Session session = sf.openSession();
session.beginTransaction();
// getting the object using load method instead of using get method
Employee emp = (Employee) session.load(Employee.class, 1);
session.delete(emp);
System.out.println("Employee Deleted");
session.getTransaction().commit();
session.clear();
}



}
To test the main class uncomment the method in main method one by one to test each operation.

Thanks and Happy Learniing