Home » Hibernate » CRUD Operations Using Hibernate

CRUD Operations Using Hibernate

A CRUD operation deals with creating , retrieving , updating and deleting records from the table, in this tutorial we will see how it is done.We are going to discuss about 4 main functionality:

  • Create a record
  • Read a record
  • Update a Record
  • Delete a Record

First, lets create the database and table for Employee using the following SQL scripts.Following script will create database and table in mysql:

create database jwt;

CREATE TABLE `empcrud` (
  `ID` int(11) NOT NULL,
  `NAME` varchar(255) NOT NULL,
  `SAL` int(11) NOT NULL,
  `CITY` varchar(255) NOT NULL,
  `PHONE` int(11) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 1: Create a Java project

Create a Java project and update Hibernate jars and hibernate related jar in to build path of your project.Download Hibernate Jar from Here


Directory Structure of Project

Hibernate CRUD Example


Step 2 : Create the Persistent class

Employee.java


package com.jwt.hibernate;

import java.io.Serializable;

public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;
	private int id;
	private String name;
	private int sal;
	private String city;
	private int phone;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getSal() {
		return sal;
	}

	public void setSal(int sal) {
		this.sal = sal;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public int getPhone() {
		return phone;
	}

	public void setPhone(int phone) {
		this.phone = phone;
	}

}

Step 3 : Create Hibernate config file (hibernate.cfg.xml)

hibernate.cfg.xml


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/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/jwt</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">mukesh</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<mapping resource="com/jwt/hibernate/Employee.hbm.xml" />
	</session-factory>
</hibernate-configuration>

Step 4 : Create mapping file for Employee class

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.jwt.hibernate.Employee" table="EMPCRUD">
		<id name="id" type="integer" column="ID">
			<generator class="increment" />
		</id>
		<property name="name" type="string" column="NAME" not-null="true" />
		<property name="sal" type="integer" column="SAL" not-null="true" />
		<property name="city" type="string" column="CITY" not-null="true" />
		<property name="phone" type="integer" column="PHONE"
			not-null="true" />
	</class>
</hibernate-mapping>

Step 5 : Create utility class HibernateUtil to get SessionFactory Object

HibernateUtil.java


package com.jwt.hibernate.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;
	}
}

Step 6 : Create Main Class for database operation(CRUD)

Main.java


package com.jwt.hibernate.main;

import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.jwt.hibernate.Employee;
import com.jwt.hibernate.util.HibernateUtil;

public class Main {
	public static void main(String[] args) {
		Main main = new Main();
		main.saveEmployee("Mukesh", "CEO", 100000, 893965);
		main.saveEmployee("Ravi", "Manager", 50000, 996654);
		main.saveEmployee("Amit", "PM", 45000, 93445);
		main.retriveEmployee();
		main.deleteEmployee();
		main.updateEmployee();
	}

	public void saveEmployee(String name, String city, int sal, int phone) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;

		try {
			transaction = session.beginTransaction();
			Employee employee = new Employee();
			employee.setName("name");
			employee.setSal(sal);
			employee.setCity("city");
			employee.setPhone(phone);
			session.save(employee);
			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.getName() + "  "
						+ employee1.getCity() + "  " + employee1.getSal()
						+ "   " + employee1.getPhone());
			}
			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 phone = :phone";
			Query query = session.createQuery(queryString);
			query.setInteger("phone", 893965);
			Employee employee = (Employee) query.uniqueResult();
			session.delete(employee);
			System.out.println("Employee records 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", 50000);
			Employee employee = (Employee) query.uniqueResult();
			employee.setSal(60000);
			session.update(employee);
			System.out.println("Employee records updated!");
		} catch (HibernateException e) {

			transaction.rollback();

			e.printStackTrace();

		} finally {

			session.close();

		}
	}
}

Output :

If data is inserted into DB you can see inserted/updated/deleted data in mysql console as shown below.

Hibernate Annotation Example


Download the example developed in eclipse


Previous Next Article

comments powered by Disqus