In this Hibernate CRUD Example, we will learn how to use Hibernate to perform CRUD operations using XML Mapping. We will be using Oracle database and build an Employee Management System which has the capabilities of Creating a new employee, Getting all the employees, Update the existing employee, Delete an employee.
Creating table
Create EMPLOYEE Table, simply Copy and Paste the following SQL query in the query editor to get the table created.
CREATE TABLE "EMPLOYEE" ( "ID" NUMBER(10) NOT NULL ENABLE, "AGE" NUMBER(10), "DEPT" VARCHAR2(255 CHAR), "NAME" VARCHAR2(255 CHAR), PRIMARY KEY ("ID") );
Folder Structure:
- Create a simple Maven Project “HibernateTutorial” and create a package for our source files “com.javainterviewpoint” under src/main/java
- Now add the following dependency in the POM.xml
<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>HibernateTutorial</groupId> <artifactId>HibernateTutorial</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <hibernate.version>4.3.11.Final</hibernate.version> <oracle.connector.version>11.2.0</oracle.connector.version> </properties> <dependencies> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- Oracle --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>${oracle.connector.version}</version> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build>d </project>
- Create the Java classes Employee.java, EmployeeLogic.java and HibernateUtil.java under com.javainterviewpoint folder.
- Place the employee.hbm.xml and hibernate-cfg.xml under the src/main/resources directory
Hibernate CRUD Example
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.javainterviewpoint.model.Employee" table="EMPLOYEE"> <id name="id" column="ID"> <generator class="assigned" /> </id> <property name="name" column="NAME" /> <property name="age" column="AGE" /> <property name="dept" column="DEPT" /> </class> </hibernate-mapping>
- The “employee.hbm.xml” tells hibernate to map “Employee” class with the “EMPLOYEE” table in the database.
- Here ID column act as the primary hence it is marked with the <id>tag.
- <property> tag maps the property ofEmployee to the corresponding column in EMPOYEE table.
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> <!-- Database connection settings --> property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@rsh2:40051:mydb</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</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="hibernate.hbm2ddl.auto">update</property> <!-- Mapping file --> <mapping resource="employee.hbm.xml" /> </session-factory> </hibernate-configuration>
- First and foremost property is for specifying the JDBC Driver class, in my case it OracleDriver
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
- Give the connection URL for connecting the database and provide username and password for connecting the above database
<property name="hibernate.connection.url">jdbc:oracle:thin:@mydb:40051:dev</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property>
- Specify the connection pool size, this property limits the number of connections in the Hibernate connection pool.
<property name="connection.pool_size">1</property>
- Dialect Property makes the Hibernate generate the SQL for the corresponding database which is being used. In this example we are using Oracle database hence Oracle query will be generated. If you are using MySQL database then you need to change the dialect accordingly.
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
- The show_sql property will print the executed sql in the console when set to true.
<property name="show_sql">true</property>
- If the property “hibernate.hbm2ddl.auto” is set to “create” This will drop and recreate the database schema on every execution. If it is set to “update” then the database schema will be updated every time rather than dropping and recreating.
<property name="hibernate.hbm2ddl.auto">update</property>
- Under the Mapping resource tag, we need to specify all the mapping resources for which we need the table to be created or updated.
<mapping resource="employee.hbm.xml"/>
EmployeeLogic.java
package com.javainterviewpoint; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; public class EmployeeLogic { public static void main(String[] args) { EmployeeLogic el = new EmployeeLogic(); el.createEmployee(); el.readAllEmployeeDetails(); el.updateEmployeeById(2, "JIP22"); el.deleteEmployeeById(2); } //Save Employee public void createEmployee() { Employee e1 = new Employee(); e1.setName("JIP1"); e1.setId(1); e1.setAge(111); e1.setDept("Java"); Employee e2 = new Employee(); e2.setName("JIP2"); e2.setId(2); e2.setAge(222); e2.setDept("Test"); SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(e1); session.save(e2); session.getTransaction().commit(); System.out.println("Employees Created!!!"); } //Read all the saved Employees @SuppressWarnings("unchecked") public void readAllEmployeeDetails() { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); List<Employee> employeeList = (List) session.createQuery( "FROM Employee").list(); System.out.println("*** Employee Details ***"); for(Employee employee : employeeList) { System.out.println("Employee ID : "+ employee.getId()); System.out.println("Employee Name : "+ employee.getName()); System.out.println("Employee Age : "+ employee.getAge()); } session.getTransaction().commit(); } // Update Employee by Id public void updateEmployeeById(int id,String name) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, id); employee.setName(name); session.update(employee); session.getTransaction().commit(); System.out.println("Employee Updated!!!"); } // Delete Employee by Id public void deleteEmployeeById(int id) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, id); session.delete(employee); session.getTransaction().commit(); System.out.println("Employee Deleted!!!"); } }
HibernateUtil.java
package com.javainterviewpoint; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateUtil { private static SessionFactory sessionFactory; private HibernateUtil() { } public static SessionFactory getSessionFactory() { Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder(); srb.applySettings(configuration.getProperties()); ServiceRegistry serviceRegistry = srb.build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } }
We have created a separate HibernateUtil class to read the configuration file and return the sessionFactory.
- Create the Configuration object and read the configuration file using the configure() method.
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
- Get the SessionFactory object through the buildSessionFactory() method of the configuration object.
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Empoyee.java
Our Employee class is a simple POJO consisting of getters and setters for the property id, name, age, dept.
package com.javainterviewpoint; import java.io.Serializable; public class Employee implements Serializable { private static final long serialVersionUID = -889976693182180703L; private int id; private String name; private int age; private String dept; public Employee() { super(); } public Employee(int id, String name, int age, String dept) { super(); this.id = id; this.name = name; this.age = age; this.dept = dept; } 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 getAge() { return age; } public void setAge(int age) { this.age = age; } public String getDept() { return dept; } public void setDept(String dept) { this.dept = dept; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", dept=" + dept + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((dept == null) ? 0 : dept.hashCode()); result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; if (age != other.age) return false; if (dept == null) { if (other.dept != null) return false; } else if (!dept.equals(other.dept)) return false; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
Output :
Hibernate: insert into EMPLOYEE (NAME, AGE, DEPT, ID) values (?, ?, ?, ?) Hibernate: insert into EMPLOYEE (NAME, AGE, DEPT, ID) values (?, ?, ?, ?) Employees Created!!! Hibernate: select employee0_.ID as ID1_0_, employee0_.NAME as NAME2_0_, employee0_.AGE as AGE3_0_, employee0_.DEPT as DEPT4_0_ from EMPLOYEE employee0_ *** Employee Details *** Employee ID : 1 Employee Name : JIP1 Employee Age : 111 Employee ID : 2 Employee Name : JIP2 Employee Age : 222 Hibernate: select employee0_.ID as ID1_0_0_, employee0_.NAME as NAME2_0_0_, employee0_.AGE as AGE3_0_0_, employee0_.DEPT as DEPT4_0_0_ from EMPLOYEE employee0_ where employee0_.ID=? Hibernate: update EMPLOYEE set NAME=?, AGE=?, DEPT=? where ID=? Employee Updated!!! Hibernate: select employee0_.ID as ID1_0_0_, employee0_.NAME as NAME2_0_0_, employee0_.AGE as AGE3_0_0_, employee0_.DEPT as DEPT4_0_0_ from EMPLOYEE employee0_ where employee0_.ID=? Hibernate: delete from EMPLOYEE where ID=? Employee Deleted!!!
Leave a Reply