Unit 4: Hibernate and Spring
Introduction to Hibernate (HB):-
Hibernate is an ORM (Object-Relational Mapping) framework for Java. It helps map Java classes to
database tables, and from Java data types to SQL data types, so you can work with objects in Java
instead of writing JDBC/SQL everywhere. Some features:
Maps Java classes to database tables, and Java data types to SQL types.
Manages data persistence, fetching, updates, deletes.
Supports query via HQL / Criteria / JPQL, caching, lazy loading, etc.
Helps with inheritance, associations, collection types.
Hibernate is an open-source Object Relational Mapping (ORM) framework for Java. It simplifies database
connection by mapping Java classes (objects) to database tables and Java data types to SQL data types.
Instead of writing long SQL queries, developers can use Hibernate APIs or HQL (Hibernate Query
Language) to perform CRUD operations.
Hibernate acts as a bridge between Java objects and relational databases, thereby reducing the need for
boilerplate JDBC code.
Key Features of Hibernate:-
ORM (Object-Relational Mapping): Maps Java classes to database tables and Java objects to
rows, enabling object-oriented database interaction.
Database Independence: Hibernate applications can run on multiple databases with minimal
changes, providing portability.
HQL (Hibernate Query Language): Supports database-independent, object-oriented queries for
fetching and manipulating data.
Transaction Management: Integrates with JDBC or JTA to provide reliable and consistent
transaction handling.
Caching: Improves performance with first-level (session) and optional second-level caching
across sessions.
Relationship Mapping: Supports mapping of object relationships like one-to-one, one-to-many,
many-to-one and many-to-many.
Prof. Akash D
Architecture of Hibernate:-
The architecture of Hibernate is layered and consists of several key components working
together.
JNDI Stands for Java Naming and Directory Interface.
Key Components of Hibernate Architecture
1. Configuration:-
Configuration is a class which is present in [Link] package. It activates Hibernate framework.
It reads both configuration file and mapping files.
Example:
Configuration cfg = new Configuration();
[Link](); // Reads and validates [Link]
Key Points:
Activates Hibernate framework.
Reads configuration ([Link]) and mapping files.
Throws an exception if the configuration is invalid.
Creates in-memory metadata representing the configuration.
2. SessionFactory:-
Prof. Akash D
The SessionFactory interface creates Session objects and maintains a second-level cache. It is
heavyweight and thread-safe, so usually one per application.
SessionFactory factory = [Link]();
Key Points:
Factory for Session objects.
Thread-safe and heavy-weight.
One per database is sufficient.
3. Session:-
The Session interface interacts with the database and provides CRUD operations. It maintains a first-
level cache (session-level).
Session session = [Link]();
4. Transaction:-
The Transaction interface handles atomic database operations, ensuring data integrity through commit
or rollback.
Transaction tx = [Link]();
[Link](); // or [Link]();
5. Query:-
The Query interface executes HQL, Criteria API or native SQL queries to fetch or manipulate data.
Query<Student> query = [Link]("from Student");
List<Student> students = [Link]();
6. Persistent Classes (Entities):-
Java classes annotated with @Entity represent database tables. Each object maps to a row.
@Entity
class Student {
@Id
private Long id;
private String name;
Prof. Akash D
Key Points:
Represents database tables.
Mapped via annotations or XML.
Enables object-oriented access to data.
7. Mapping:-
Defines the relationship between Java classes and database tables. Can be done via annotations or XML
files.
@Entity
@Table(name="student")
class Student { ... }
Key Points:
Maps classes to tables and fields to columns.
Supports relationships: One-to-One, One-to-Many, Many-to-One, Many-to-Many.
8. JDBC Layer:-
Handles low-level database communication. Hibernate internally uses JDBC to execute SQL and retrieve
results.
Key Points:
Connects to database using JDBC API.
Executes SQL queries generated by Hibernate.
Manages connection pooling and result fetching.
Application of Hibernate (Typical usage & in Web Applications)
Typical steps in a Hibernate-based application (standalone or web):
1. Set up configuration ([Link] or programmatic), specify DB url, user, dialect, mapping
resources or annotated classes.
2. Define entity classes: annotate or map via XML.
3. Obtain SessionFactory (on application startup).
4. Obtain Session when needed (e.g. per request in web app).
5. Begin Transaction, perform operations (save, update, delete, query), commit or rollback.
6. Close Session.
In a web application:
Probably use a layered architecture: controller / servlet / web layer → service → DAO layer.
The DAO layer uses Hibernate to persist/retrieve entities.
Session management: one Session per request (often via a filter or interceptor), or via
integration with frameworks like Spring.
Use transaction management, either manual or via container (Spring’s @Transactional).
Prof. Akash D
JSP / JSF / REST endpoint uses the service layer.
Hibernate with Annotation:-
What is Hibernate with Annotation?
Hibernate with annotation means using Java Persistence API (JPA) annotations to map Java classes and
their fields to database tables and columns.
Instead of writing mappings in an XML file (.[Link]), you decorate your POJO (Plain Old Java Object)
classes with annotations like @Entity, @Table, @Id, @Column, etc.
Why Use Annotations?
Cleaner than XML-based mapping.
Easier to maintain and debug.
Part of JPA standard, so works with many ORM tools.
Faster development and fewer configuration files.
Hibernate with Annotation: Example Project
Let’s create a basic Hibernate project using annotation-based configuration.
Project Structure:
hibernate-annotation-example/
├── src/
│ └── com/example/
│ ├── [Link]
│ └── [Link]
├── [Link]
├── [Link] (if using Maven)
Step 1: Add Maven Dependencies ([Link])
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>hibernate-annotation-example</artifactId>
Prof. Akash D
<version>1.0</version>
<dependencies>
<!-- Hibernate Core -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>
<!-- JPA API -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>2.2.3</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.30</version>
Prof. Akash D
</dependency>
</dependencies>
</project>
Step 2: [Link] Configuration
Place this file in src/main/resources/ or in root of src/ if not using Maven.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"[Link]
<hibernate-configuration>
<session-factory>
<!-- DB connection settings -->
<property name="[Link].driver_class">[Link]</property>
<property name="[Link]">jdbc:mysql://localhost:3306/testdb</property>
<property name="[Link]">root</property>
<property name="[Link]">your_password</property>
<!-- Dialect -->
<property name="[Link]">[Link].MySQL8Dialect</property>
<!-- Show SQL -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- Update schema automatically -->
<property name="[Link]">update</property>
<!-- Annotated class -->
Prof. Akash D
<mapping class="[Link]"/>
</session-factory>
</hibernate-configuration>
Step 3: [Link] (Model Class with Annotations)
package [Link];
import [Link].*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = [Link])
private int id;
@Column(name = "emp_name")
private String name;
@Column(name = "emp_salary")
private double salary;
// Constructors
public Employee() {}
public Employee(String name, double salary) {
[Link] = name;
[Link] = salary;
// Getters & Setters
Prof. Akash D
public int getId() { return id; }
public void setId(int id) { [Link] = id; }
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public double getSalary() { return salary; }
public void setSalary(double salary) { [Link] = salary; }
Step 4: [Link] (To Run Hibernate)
package [Link];
import [Link];
import [Link];
import [Link];
public class HibernateMain {
public static void main(String[] args) {
// Load config and build SessionFactory
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.buildSessionFactory();
// Get session
Session session = [Link]();
try {
Prof. Akash D
// Create new Employee object
Employee emp = new Employee("John Doe", 50000.0);
// Start transaction
[Link]();
// Save Employee
[Link](emp);
// Commit
[Link]().commit();
[Link]("Employee saved: " + [Link]());
} finally {
[Link]();
Output (Sample Console Log):
Hibernate:
insert
into
employee
(emp_name, emp_salary)
values
(?, ?)
Employee saved: 1
Note:-(Also Refer to [Link]
Prof. Akash D
Hibernate Web Application:-
A web application with hibernate is easier. A JSP page is the best way to get user inputs. Those inputs
are passed to the servlet and finally, it is inserted into the database by using hibernate. Here JSP page is
used for the presentation logic. Servlet class is meant for the controller layer. DAO class is meant for
database access codes.
What is a Hibernate Web Application?
A Hibernate Web Application is a Java web project (using JSP + Servlet) that connects to a database
using Hibernate (ORM) to perform tasks like:
Adding records (Create)
Viewing records (Read)
Updating records (Update)
Deleting records (Delete)
Simple Example: Employee Management App
We’ll build a simple app to:
Add employees using a form.
Display all employees from the database.
Technology Used:
Component Tool
Frontend JSP
Backend Servlet
ORM Hibernate
Database MySQL
Server Apache Tomcat
Project Overview
We will have:
1. JSP Form: To take user input (name, department, salary).
2. Servlet: To receive that input and call Hibernate.
3. Hibernate: To save or read data from the database.
4. MySQL DB: To store employee data.
Step 1: Create MySQL Table
Prof. Akash D
Open MySQL and create a database and table:
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE employee (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
department VARCHAR(100),
salary DOUBLE
);
Step 2: Create Java Class [Link]
import [Link].*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = [Link])
private int id;
private String name;
private String department;
private double salary;
// Getters and Setters
Step 3: Hibernate Configuration [Link]
Prof. Akash D
Put this file in your src/ folder.
<hibernate-configuration>
<session-factory>
<property name="[Link].driver_class">[Link]</property>
<property name="[Link]">jdbc:mysql://localhost:3306/testdb</property>
<property name="[Link]">root</property>
<property name="[Link]">your_password</property>
<property name="[Link]">[Link].MySQL8Dialect</property>
<property name="[Link]">update</property>
<mapping class="Employee"/>
</session-factory>
</hibernate-configuration>
Step 4: Hibernate Utility Class [Link]
import [Link];
import [Link];
public class HibernateUtil {
private static final SessionFactory factory;
static {
factory = new Configuration().configure().buildSessionFactory();
public static SessionFactory getSessionFactory() {
return factory;
Prof. Akash D
This sets up Hibernate to connect with MySQL.
Step 5: Servlet [Link]
import [Link].*;
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
@WebServlet("/employee")
public class EmployeeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Read data from form
String name = [Link]("name");
String department = [Link]("department");
double salary = [Link]([Link]("salary"));
// Create Employee object
Employee emp = new Employee();
[Link](name);
[Link](department);
[Link](salary);
// Save using Hibernate
Session session = [Link]().openSession();
Transaction tx = [Link]();
Prof. Akash D
[Link](emp);
[Link]();
[Link]();
[Link]().println("Employee saved!");
Step 6: JSP Form [Link]
<!DOCTYPE html>
<html>
<head><title>Add Employee</title></head>
<body>
<h2>Add Employee</h2>
<form action="employee" method="post">
Name: <input type="text" name="name"><br>
Department: <input type="text" name="department"><br>
Salary: <input type="text" name="salary"><br>
<input type="submit" value="Save Employee">
</form>
</body>
</html>
Step 7: [Link] Configuration (Optional if using annotations)
<web-app>
<display-name>Hibernate Web App</display-name>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
Prof. Akash D
How It Works(Run):-
Open your browser and go to:
[Link]
Fill the form and click Submit.
The Servlet reads the form → uses Hibernate → saves data to MySQL.
Project Structure:-
HibernateWebApp/
├── src/main/
│ ├── java/
│ │ └── com/example/
│ │ ├── model/
│ │ │ └── [Link]
│ │ ├── dao/
│ │ │ └── [Link]
│ │ ├── servlet/
│ │ │ └── [Link]
│ │ └── util/
│ │ └── [Link]
│ │
│ └── resources/
│ └── [Link]
├── src/main/webapp/
│ ├── [Link]
│ ├── [Link]
│ └── WEB-INF/
│ └── [Link]
├── [Link]
Prof. Akash D
└── [Link] (optional)
Note:-(Also Refers the [Link]
Inheritance Mapping in Hibernate:-
The inheritance hierarchy can be seen easily in the table of the database. In Hibernate we have
three different strategies available for Inheritance Mapping
Table Per Hierarchy
Table Per Concrete class
Table Per Subclass
What is Inheritance Mapping in Hibernate?
In object-oriented programming (OOP), inheritance allows one class (child) to inherit fields and methods
from another (parent).
In databases, there's no native inheritance — so Hibernate provides strategies to map an inheritance
hierarchy of classes into relational tables.
Inheritance Mapping Strategies in Hibernate:-
Hibernate supports three inheritance mapping strategies via JPA annotations:
Strategy Description Annotation
Table Per All classes stored in one @Inheritance(strategy =
Hierarchy (TPH) table InheritanceType.SINGLE_TABLE)
Table Per
Each class has its own @Inheritance(strategy =
Concrete Class InheritanceType.TABLE_PER_CLASS)
table
(TPC)
Parent and each subclass
Table Per @Inheritance(strategy =
have separate, related [Link])
Subclass (TPS)
tables
1. Table Per Hierarchy (TPH):-
All classes in the inheritance hierarchy are mapped to a single database table.
Characteristics:
Uses a discriminator column to identify subclass type.
Fast queries.
May result in many null columns (fields not used by all subclasses).
Prof. Akash D
Example:-
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public class Vehicle {
@Id
int id;
String name;
@Entity
@DiscriminatorValue("Car")
public class Car extends Vehicle {
int numberOfDoors;
@Entity
@DiscriminatorValue("Bike")
public class Bike extends Vehicle {
boolean hasCarrier;
Database Table (Only 1 Table!):
id name type numberOfDoors hasCarrier
1 Swift Car 4 NULL
2 Hero Bike NULL true
Advantages:
Prof. Akash D
One table only
Easy and fast
Disadvantages:
Unused columns are NULL
2. Table Per Concrete Class (TPC):-
Each concrete (non-abstract) class has its own separate table with all fields, including inherited ones.
Characteristics:
No joins.
No discriminator column.
Duplicate columns for inherited fields in each table.
Example:-
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
@Id
int id;
String name;
@Entity
public class Car extends Vehicle {
int numberOfDoors;
@Entity
public class Bike extends Vehicle {
boolean hasCarrier;
Tables:(Car Table:)
Prof. Akash D
id name numberOfDoors
1 Swift 4
Bike Table:
id name hasCarrier
2 Hero true
Advantages:
No NULL values
Clear table per class
Disadvantages:
Repeated columns (like name in both tables)
No one common table
3. Table Per Subclass (TPS):-
Parent class and each subclass have their own table, and are joined via primary key (foreign key
relationship).
Characteristics:
Normalized design (no null columns).
Uses JOINs for subclass queries.
More complex queries but cleaner schema.
Example:-
@Entity
@Inheritance(strategy = [Link])
public class Vehicle {
@Id
int id;
String name;
@Entity
Prof. Akash D
public class Car extends Vehicle {
int numberOfDoors;
@Entity
public class Bike extends Vehicle {
boolean hasCarrier;
Tables:
Vehicle Table:
id name
1 Swift
2 Hero
Car Table:
id numberOfDoors
1 4
Bike Table:
id hasCarrier
2 true
Hibernate joins these tables when you query.
Advantages:
Clean tables
No NULLs
Normalized
Disadvantages:
Slower because of JOINs
Note-(Also Refer to [Link]
Prof. Akash D
Hibernate Collection Mapping:-
In Hibernate, Collection Mapping refers to how we map Java collection types like List, Set, Map,
and Bag in entity classes to one-to-many or many-to-many relationships in the database.
These mappings are useful when:
An entity contains multiple child entities (e.g., a Department has many Employees)
The collection needs to be ordered, unique, indexed, or key-based
1. List Mapping:-
Type: Ordered and indexed collection (can contain duplicates)
DB Table: Stores order via an index column
Behavior:
Allows duplicates
Keeps order
Example:- One-to-Many with List
@Entity
public class Department {
@Id
private int id;
private String name;
@OneToMany(cascade = [Link])
@JoinColumn(name = "dept_id") // FK in employee table
@OrderColumn(name = "position") // saves order
private List<Employee> employees;
@Entity
public class Employee {
@Id
private int id;
Prof. Akash D
private String name;
2. Set Mapping:-
Type: Unordered collection with no duplicates
Hibernate uses a HashSet by default
Behavior:
Does NOT allow duplicates
Order is NOT saved
Example: One-to-Many with Set
@Entity
public class Department {
@Id
private int id;
private String name;
@OneToMany(cascade = [Link])
@JoinColumn(name = "dept_id")
private Set<Employee> employees = new HashSet<>();
3. Bag Mapping:-
Type: Unordered collection that allows duplicates
Similar to a List but doesn't store order.
Hibernate internally uses a Bag type for mapping collections like List without @OrderColumn
Behavior:
Allows duplicates
No order
Internally uses List, but no @OrderColumn
Example: One-to-Many with Bag
@Entity
public class Department {
Prof. Akash D
@Id
private int id;
private String name;
@OneToMany(cascade = [Link])
@JoinColumn(name = "dept_id")
private Collection<Employee> employees = new ArrayList<>();
4. Map Mapping:-
Type: Key-Value mapping
You can use an attribute of the child as the key (e.g., employee name)
Behavior:
You map Key -> Value
For example: "empName" -> Employee
Example: One-to-Many with Map
@Entity
public class Department {
@Id
private int id;
private String name;
@OneToMany(cascade = [Link])
@JoinColumn(name = "dept_id")
@MapKey(name = "name") // use 'name' field of Employee as key
private Map<String, Employee> employees;
@Entity
public class Employee {
Prof. Akash D
@Id
private int id;
private String name;
Project Structure Overview:-
src/
├── model/
│ ├── [Link]
│ └── [Link]
├── [Link]
└── [Link]
Note:-(Also Refer To [Link] ).
Prof. Akash D