In previous post Save and persist an entity example in hibernate you learnt how to save an entity object in database.
This post demonstrates how to perform CRUD(Create,Read,Update and Delete) operation is hibernate step by step.
Technologies and tools used for this application are –
- Hibernate 5.2.11.Final
- Eclipse Mars.2 (4.5.0)
- Maven 3.5.0
- JavaSE 1.8
- MySQL 5.5.57
Project Structure
Review the following project structure.
Step 1 – Create a maven project
Refer below link if you don’t know how to create Maven project in eclipse:
How to create Maven project
Step 2 – Add jar dependencies to pom.xml
below is the pom.xml file and add required Hibernate and MySQL connector dependencies to it.
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.infotech</groupId> <artifactId>HibernateReadUpdateAndDeleteExample</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- MySQL connector dependency --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <!-- Hibernate 5.2.11 Final dependency--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.11.Final</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> |
Step 3 – Create Entity class in hibernate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
package com.infotech.entities; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.DynamicUpdate; @Entity @Table(name="employee_table") @DynamicUpdate public class Employee { @Id @Column(name="employee_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer employeeId; @Column(name="employee_name",length=100,nullable=false) private String employeeName; @Column(name="email",unique=true) private String email; @Column(name="date_of_joing") private Date doj; @Column(name="salary") private Double salary; public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getDoj() { return doj; } public void setDoj(Date doj) { this.doj = doj; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } @Override public String toString() { return "Employee [employeeId=" + employeeId + ", employeeName=" + employeeName + ", email=" + email + ", doj=" + doj + ", salary=" + salary + "]"; } } |
Step 4 – Create a Hibernate configuration file
Create an XML file named as hibernate.cfg.xml under src/main/resources folder and write the following code in it.
hibernate.cfg.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:4406/test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <mapping class="com.infotech.entities.Employee"/> </session-factory> </hibernate-configuration> |
Step 5 – Hibernate utility class which is responsible to provide SessionFactory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package com.infotech.util; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; /** * @author kishan Kumar */ public class HibernateUtil { private static StandardServiceRegistry standardServiceRegistry; private static SessionFactory sessionFactory; static{ if (sessionFactory == null) { try { // Create StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder() .configure() .build(); // Create MetadataSources MetadataSources metadataSources = new MetadataSources(standardServiceRegistry); // Create Metadata Metadata metadata = metadataSources.getMetadataBuilder().build(); // Create SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); } catch (Exception e) { e.printStackTrace(); if (standardServiceRegistry != null) { StandardServiceRegistryBuilder.destroy(standardServiceRegistry); } } } } //Utility method to return SessionFactory public static SessionFactory getSessionFactory() { return sessionFactory; } } |
Step 6 – Create service interface and it’s implementation class
1 2 3 4 5 6 7 8 9 10 |
package com.infotech.service; import com.infotech.entities.Employee; public interface EmployeeService { public abstract void createEmployee(Employee employee); public abstract Employee getEmployeebyId(int employeeId); public abstract void updateEmployeeById(int employeeId,Double newSal); public abstract void deleteEmployeeById(Integer employeeId); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.infotech.service.impl; import com.infotech.dao.impl.EmployeeDAOImpl; import com.infotech.entities.Employee; import com.infotech.service.EmployeeService; public class EmployeeServiceImpl implements EmployeeService { @Override public void createEmployee(Employee employee) { new EmployeeDAOImpl().addEmployee(employee); } @Override public Employee getEmployeebyId(int employeeId) { return new EmployeeDAOImpl().fetchEmployeebyId(employeeId); } @Override public void updateEmployeeById(int employeeId, Double newSal) { new EmployeeDAOImpl().updateEmployeeById(employeeId, newSal); } @Override public void deleteEmployeeById(Integer employeeId) { new EmployeeDAOImpl().deleteEmployeeById(employeeId); } } |
Step 7 –Create DAO(Data access object) interface and it’s implementation class
1 2 3 4 5 6 7 8 9 |
package com.infotech.dao; import com.infotech.entities.Employee; public interface EmployeeDAO { public abstract void addEmployee(Employee employee); public abstract Employee fetchEmployeebyId(int employeeId); public abstract void updateEmployeeById(int employeeId,Double newSal); public abstract void deleteEmployeeById(Integer employeeId); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
package com.infotech.dao.impl; import org.hibernate.HibernateException; import org.hibernate.Session; import com.infotech.dao.EmployeeDAO; import com.infotech.entities.Employee; import com.infotech.util.HibernateUtil; public class EmployeeDAOImpl implements EmployeeDAO { @Override public void addEmployee(Employee employee) { try (Session session = HibernateUtil.getSessionFactory().openSession()) { session.beginTransaction(); Integer id =(Integer)session.save(employee); System.out.println("Employee is created with Id::"+id); session.getTransaction().commit(); } catch (HibernateException e) { e.printStackTrace(); } } @Override public Employee fetchEmployeebyId(int employeeId) { Employee employee = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { employee = session.get(Employee.class,employeeId ); if(employee != null){ return employee; }else{ System.out.println("Employee doesn't exist with provideded Id.."); } } catch (HibernateException e) { e.printStackTrace(); } return null; } @Override public void updateEmployeeById(int employeeId, Double newSal) { try (Session session = HibernateUtil.getSessionFactory().openSession()) { Employee employee = session.get(Employee.class, employeeId); if(employee != null){ employee.setSalary(newSal); session.beginTransaction(); session.update(employee); session.getTransaction().commit(); }else{ System.out.println("Employee doesn't exist with provideded Id.."); } } catch (HibernateException e) { e.printStackTrace(); } } @Override public void deleteEmployeeById(Integer employeeId) { try (Session session = HibernateUtil.getSessionFactory().openSession()) { Employee employee = session.get(Employee.class, employeeId); if(employee != null){ session.beginTransaction(); session.delete(employee); session.getTransaction().commit(); }else{ System.out.println("Employee doesn't exist with provideded Id.."); } } catch (HibernateException e) { e.printStackTrace(); } } } |
Step 8 – Now create client program with main method to perform CRUD operation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.infotech.client; import java.util.Date; import com.infotech.entities.Employee; import com.infotech.service.EmployeeService; import com.infotech.service.impl.EmployeeServiceImpl; public class ClientTest { public static void main(String[] args) { EmployeeService employeeService = new EmployeeServiceImpl(); createEmployee(employeeService); //getEmployeebyId(employeeService); //updateEmployeeById(employeeService); //deleteEmployeeById(employeeService); } private static void deleteEmployeeById(EmployeeService employeeService) { employeeService.deleteEmployeeById(1); } private static void updateEmployeeById(EmployeeService employeeService) { employeeService.updateEmployeeById(1, 60000.00); } private static void getEmployeebyId(EmployeeService employeeService) { Employee employee = employeeService.getEmployeebyId(1); System.out.println(employee); } private static void createEmployee(EmployeeService employeeService) { employeeService.createEmployee(getEmployee()); } private static Employee getEmployee(){ Employee employee= new Employee(); employee.setEmployeeName("Martin Bingel"); employee.setSalary(50000.00); employee.setDoj(new Date()); return employee; } } |
That’s all about Hibernate CRUD example
You May Also Like:
Latest hibernate distribution Zip file download link
Hibernate 5 distribution binary details
Create SessionFactory in Hibernate5 using hibernate.cfg.xml
Create SessionFactory in Hibernate5 without hibernate.cfg.xml
Save and persist an entity example in hibernate
Dirty checking in hibernate example
Understanding hibernate Configuration File
Why to use hibernate dialect?
Hibernate hbm2ddl property
What are the benefits of using hibernate?
If you have any feedback or suggestion please feel free to drop in below comment box.