In previous post Hibernate CRUD example in hibernate you learnt how to perform Create,Read,Update and Delete operation with database.In this post I will demonstrate about Dirty checking in hibernate example step by step using below project.
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>HibernateDirtyCheckingExample</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 71 |
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 41 |
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 5 – Create two client classes
SavingEntityClientTest.java->This client class used to save entity object in database.
DirtyCheckingClientTest.java->This client class shows how dirty checks works 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 |
package com.infotech.client; import java.util.Date; import org.hibernate.Session; import com.infotech.entities.Employee; import com.infotech.util.HibernateUtil; public class SavingEntityClientTest { public static void main(String[] args) { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); createEmployee(session); } catch (Exception e) { e.printStackTrace(); }finally { if(session != null){ session.close(); } } } private static void createEmployee(Session session) { session.beginTransaction(); Integer id =(Integer)session.save(getEmployee()); System.out.println("Employee is created with Id::"+id); session.getTransaction().commit(); } private static Employee getEmployee(){ Employee employee= new Employee(); employee.setEmployeeName("Martin Bingel"); employee.setSalary(50000.00); employee.setDoj(new Date()); return employee; } } |
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 |
package com.infotech.client; import org.hibernate.Session; import com.infotech.entities.Employee; import com.infotech.util.HibernateUtil; public class DirtyCheckingClientTest { public static void main(String[] args) { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); Employee employee = session.get(Employee.class, 1); if(employee != null){ session.beginTransaction(); employee.setSalary(40000.00); employee.setEmployeeName("Martin Bingel2"); //session.update(employee);//Even though you comment this line still // hibernate triggers update query if employee salary or name different //in the database this feature is called dirty checking in hibernate session.getTransaction().commit(); //employee.setEmployeeName("Martin Bingel2"); }else{ System.out.println("Employeedoesn't exist with provided Id.."); } } catch (Exception e) { e.printStackTrace(); }finally { if(session != null){ session.close(); } } } } |