Show List

Hibernate

Hibernate is an implementation of JPA. It uses Hibernate Query Language (HQL) to execute database operations. Hibernate is a wrapper over JDBC API. 

Advantages of Hibernate

  • Hibernate code will work across different databases. E.g. Oracle, MySQL.
  • SQL knowledge is not required.
  • Query tuning is automatically done in Hibernate to provide best performance.
  • Utilizes cache for better performance
  • Hibernate connects with the database itself and uses HQL (Hibernate query language) to execute queries.
  • Results of retrieve (select) queries are mapped to the Java objects.
  • Database connection is created using session which helps in saving and retrieving the persistent object.
  • Supports lazy loading which helps load the initial results faster.
  • In JDBC we have to use try catch to handle various exceptions. Hibernate converts all JDBC exceptions to unchecked exceptions so there is no need to write try catch blocks.
  • In Hibernate we do not have to explicitly commit or rollback the transactions. Transaction management is provided by Hibernate implicitly.
  • Hibernate provides connection pooling.

Steps to use Hibernate in a Java Program

Using xml based mapping (Without using Spring):
  • Add Hibernate jar and database connection jar to the classpath
  • Create Entity Classes (Without @Entity, @Id and other annotations)
package net.itcodescanner.entities;

public class Employee {

private int id;
private String name;
private String address;


private Department department;

public Employee() {
}

public Employee( String name, String address) {
this.name = name;
this.address = address;
}

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 String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}
  • Create Dao Classes
  • Create xml file mapping Entity Classes to database tables
<hibernate-mapping>
<class name="net.demo.entities.Employee" table="employees">
<id name="id" type="java.lang.int">
<column name="empnum" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="empname" length="45" not-null="true" />
</property>
<property name="address" type="string">
<column name="address" length="200" not-null="true" />
</property>
<property name="deptnum" type="java.lang.int">
<column name="deptnum" length="255" not-null="true" />
</property>
</class>
</hibernate-mapping>
  • Create Hibernate configuration xml file that would provide the connection url, user name, password, driver set other properties for hibernate
<?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>

<!-- Set URL -->
<property name = "hibernate.connection.url">jdbc:mysql://localhost:3306/demo(your schema name)</property>

<!-- Set User Name -->
<property name = "hibernate.connection.username">your MySQL user name</property>

<!-- Set Password -->
<property name = "hibernate.connection.password">your MySQL password</property>

<!-- Set Driver Name -->
<property name = "hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

<property name = "hibernate.show_sql">true</property>

</session-factory>
</hibernate-configuration>
  • Add the logic in the application to get Hibernate session object and call methods. Hibernate uses session to communicate with database.
public class Application {

public static void main(String[] args){
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try (SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory()) {
EmployeeDao employeeDAO = new EmployeeDao(sessionFactory);
DepartmentDao departmentDAO = new DepartmentDao(sessionFactory);


try (Session session = sessionFactory.getCurrentSession()) {
Transaction tx = session.beginTransaction();
// create departments
Department pj = departmentDAO.save(new Department("Department-21"));
Department px = departmentDAO.save(new Department("Department-22"));
employeeDAO.save(new Employee("EmpName-1", "Address-32", pj));
employeeDAO.save(new Employee("EmpName-2", "Address-54", px));
tx.commit();
}

try (Session session = sessionFactory.getCurrentSession()) {
session.beginTransaction();
System.out.println("Employees");
employeeDAO.list().forEach(employee -> System.out.println(employee.getId() +", " + employee.getName() + ", " + employee.getAddress() + ", " + employee.getDepartment().getName() ));
System.out.println("Departments");
departmentDAO.list().forEach(department -> System.out.println(department.getName() + ", " + department.getId()));
}
}
}
}




Using annotation based mapping: 
Here Database mapping will be provided in the Entity classes so xml mapping file will not be required. Mapping classes are listed in the Hibernate configuration xml file. So the steps are:

  • Add Hibernate jar and database connection jar to the classpath
  • Create Entity Classes (Provide @Entity, @Id and other annotations)
package net.itcodescanner.entities;


import javax.persistence.*;

@Entity
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String address;

@ManyToOne
@JoinColumn(foreignKey = @ForeignKey(name = "fk_employee_department"))
private Department department;

public Employee() {
}

public Employee( String name, String address, Department department) {
this.name = name;
this.address = address;
this.department = department;
}

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 String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public Department getDepartment() {
return department;
}

public void setDepartment(Department department) {
this.department = department;
}
}
  • Create Dao Classes
XML file mapping Entity Classes to database tables is not required.

  • Create Hibernate configuration xml file that would provide the connection url, user name, password, driver set other properties for hibernate
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:./data/db</property>
<property name="connection.username">sa</property>
<property name="connection.password"/>
<property name="dialect">org.hibernate.dialect.H2Dialect</property>

<property name="hbm2ddl.auto">create</property>

<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<mapping class="net.itcodescanner.entities.Employee"/>
<mapping class="net.itcodescanner.entities.Department"/>
</session-factory>
</hibernate-configuration>
  • Add the logic in the application to get Hibernate session object and call methods.


Using Spring Boot:
Add JPA and selected database as the dependency for the Spring Boot project. Hibernate is used as default implementation for JPA in Spring Boot. @EnableTransactionManagement annotation on the main class takes care of transactions. We do not need to write the code to get the session.

Spring also provides CrudRepository interface so we do not have to write the code for CRUD methods.

Properties such as show-sql can be added in the src\main\resources\application.properties  file.
  • Create Spring Boot application with JPA and database dependency
  • Add @EnableTransactionManagement annotation on the main class
package com.example.demo;

import com.example.demo.service.DataProcessingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
  • Create Entity Classes
  • Create Repositories (DAO classes) extending CrudRepository
package com.example.demo.dao;

import com.example.demo.entities.Employee;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeDao extends CrudRepository<Employee, Long> {} 
  • Add properties in the application.properties file
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
  • Create service to perform database operations
 package com.example.demo.service;

import com.example.demo.dao.DepartmentDao;
import com.example.demo.dao.EmployeeDao;
import com.example.demo.entities.Department;
import com.example.demo.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DataProcessingService {
@Autowired
private EmployeeDao employeeDao;

@Autowired
private DepartmentDao departmentDao;

public void insertData(){
Department d1 = new Department("Department-21");
Department d2 = new Department("Department-22");

departmentDao.save(d1);
departmentDao.save(d2);

Employee e1 = new Employee("EmpName-1", "Address-32", d1);
Employee e2 = new Employee("EmpName-2", "Address-54", d2);

employeeDao.save(e1);
employeeDao.save(e2);
}

public void printData(){
System.out.println("Employees");
employeeDao.findAll().forEach(employee -> System.out.println(employee.getId() +", " + employee.getName() + ", " + employee.getAddress() + ", " + employee.getDepartment().getName() ));
System.out.println("Departments");
departmentDao.findAll().forEach(department -> System.out.println(department.getName() + ", " + department.getId()));

}
}
  • Call the service from the program

    Leave a Comment


  • captcha text