Hibernate Architecture Explained in Depth
Learn Hibernate Architecture in depth including SessionFactory, Session, Persistence Context, Entity Lifecycle, First Level Cache, Second Level Cache, Dirty Checking, Hibernate Internals, and Enterprise Architecture.
What You Will Learn
- What is Hibernate?
- Why Hibernate was created
- Hibernate Architecture
- Core Components
- SessionFactory
- Session
- Persistence Context
- Entity Lifecycle
- Dirty Checking
- Caching
- Internal Execution Flow
- Enterprise Architecture
- Interview Questions
Introduction
Before Hibernate, developers used:
JDBC
↓
Write SQL
↓
Map ResultSet
↓
Manage Connections
↓
Handle Transactions
Lots of boilerplate code.
Example:
Connection connection;
PreparedStatement ps;
ResultSet rs;
while(rs.next()) {
}
Repeated everywhere.
What is Hibernate?
Hibernate is an ORM Framework.
ORM stands for:
Object Relational Mapping
Hibernate maps:
Java Objects
↔
Database Tables
Without Hibernate
flowchart LR
A[Java Object]
B[Manual SQL]
C[Database]
A --> B
B --> C
Developer writes everything.
With Hibernate
flowchart LR
A[Java Object]
B[Hibernate]
C[Database]
A --> B
B --> C
Hibernate generates SQL automatically.
Why Hibernate?
Problems with JDBC:
Too Much Boilerplate
Manual Mapping
Manual Transactions
Manual Resource Cleanup
Database Dependency
Hibernate solves these.
Hibernate Architecture
flowchart LR
A[Java Application]
B[Hibernate API]
C[SessionFactory]
D[Session]
E[JDBC]
F[Database]
A --> B
B --> C
C --> D
D --> E
E --> F
Hibernate Components
Configuration
SessionFactory
Session
Transaction
Query
Persistence Context
Cache
Complete Hibernate Flow
flowchart LR
A[Entity]
B[Session]
C[Persistence Context]
D[Hibernate]
E[JDBC]
F[Database]
A --> B
B --> C
C --> D
D --> E
E --> F
Sample Database Table
CREATE TABLE USERS(
ID BIGINT PRIMARY KEY,
NAME VARCHAR(100),
EMAIL VARCHAR(100)
);
Equivalent Entity
@Entity
@Table(name="USERS")
public class User {
@Id
private Long id;
private String name;
private String email;
}
Hibernate automatically maps:
User Class
↓
USERS Table
Configuration Object
Loads Hibernate configuration.
Example:
Configuration configuration =
new Configuration();
configuration.configure();
Reads:
hibernate.cfg.xml
or
application.yml
SessionFactory
Most important Hibernate object.
Purpose:
Creates Sessions
SessionFactory Architecture
flowchart LR
A[Configuration]
B[SessionFactory]
C[Session]
A --> B
B --> C
SessionFactory Example
SessionFactory sessionFactory =
configuration
.buildSessionFactory();
Characteristics
Heavy Object
Thread Safe
Created Once
Application Scope
Enterprise Example
Usually:
@Bean
public SessionFactory
sessionFactory() {
}
Created once during startup.
Session
Session is:
Database Conversation
Think of it as:
Hibernate Connection Wrapper
Session Flow
flowchart LR
A[SessionFactory]
B[Session]
C[Database]
A --> B
B --> C
Session Example
Session session =
sessionFactory.openSession();
CRUD Example
User user =
session.get(
User.class,
1L
);
Hibernate automatically generates:
SELECT *
FROM USERS
WHERE ID=1;
Save Example
User user = new User();
user.setId(1L);
user.setName("Venu");
session.save(user);
Generated SQL:
INSERT INTO USERS
VALUES(1,'Venu');
Update Example
User user =
session.get(
User.class,
1L
);
user.setName("John");
No SQL written.
Hibernate detects changes automatically.
Delete Example
session.remove(user);
Generated SQL:
DELETE FROM USERS
WHERE ID=1;
Persistence Context
Most important Hibernate concept.
Persistence Context is:
First Level Cache
+
Entity Tracking
Persistence Context Architecture
flowchart LR
A[Session]
B[Persistence Context]
C[Database]
A --> B
B --> C
Example
First Query:
User user1 =
session.get(
User.class,
1L
);
SQL executed.
Second Query:
User user2 =
session.get(
User.class,
1L
);
No SQL executed.
Why?
Loaded From Cache
First Level Cache
Every Session contains:
First Level Cache
First Level Cache Flow
flowchart LR
A[Session]
B[First Level Cache]
C[Database]
A --> B
B --> C
Example
User user1 =
session.get(User.class,1L);
User user2 =
session.get(User.class,1L);
Only one SQL query.
Entity Lifecycle
Hibernate manages entities in different states.
Transient
Persistent
Detached
Removed
Lifecycle Diagram
flowchart LR
A[Transient]
B[Persistent]
C[Detached]
D[Removed]
A --> B
B --> C
B --> D
Transient State
Object exists only in memory.
User user = new User();
Not tracked.
No database record.
Persistent State
session.save(user);
Hibernate tracks changes.
Detached State
session.close();
Entity still exists.
No longer tracked.
Removed State
session.remove(user);
Marked for deletion.
Dirty Checking
Hibernate automatically detects changes.
Example
User user =
session.get(
User.class,
1L
);
user.setName("David");
No update query written.
Hibernate detects modification.
Dirty Checking Flow
flowchart LR
A[Load Entity]
B[Modify Entity]
C[Hibernate Detects]
D[Generate Update SQL]
A --> B
B --> C
C --> D
Generated SQL
UPDATE USERS
SET NAME='David'
WHERE ID=1;
Transaction Management
Transaction tx =
session.beginTransaction();
session.save(user);
tx.commit();
Transaction Architecture
flowchart LR
A[Session]
B[Transaction]
C[Database]
A --> B
B --> C
Query Execution
Hibernate supports:
HQL
Criteria API
Native SQL
JPQL
HQL Example
List<User> users =
session.createQuery(
"FROM User",
User.class
).getResultList();
Generated SQL:
SELECT *
FROM USERS;
Hibernate Cache Architecture
flowchart LR
A[Application]
B[First Level Cache]
C[Second Level Cache]
D[Database]
A --> B
B --> C
C --> D
First Level Cache
Session Scoped
Enabled By Default
Second Level Cache
Application Scoped
Optional
Popular Providers:
EhCache
Hazelcast
Redis
Infinispan
Cache Flow
flowchart LR
A[Entity Request]
B[L1 Cache]
C[L2 Cache]
D[Database]
A --> B
B --> C
C --> D
Hibernate Internal Execution Flow
flowchart LR
A[Entity]
B[Session]
C[Persistence Context]
D[SQL Generation]
E[JDBC]
F[Database]
A --> B
B --> C
C --> D
D --> E
E --> F
Real Spring Boot Architecture
flowchart LR
A[Controller]
B[Service]
C[Repository]
D[Hibernate]
E[JDBC]
F[Database]
A --> B
B --> C
C --> D
D --> E
E --> F
Banking Example
Fund Transfer API:
Transfer Request
↓
Service Layer
↓
Hibernate
↓
Oracle DB
Hibernate handles:
Transactions
Caching
Object Mapping
Advantages
✅ Less Boilerplate Code
✅ Automatic SQL Generation
✅ ORM Support
✅ Caching
✅ Transaction Management
✅ Relationship Mapping
Limitations
❌ Learning Curve
❌ ORM Overhead
❌ Hidden SQL
❌ N+1 Query Problem
❌ Performance Tuning Needed
Hibernate vs JDBC
| Feature | JDBC | Hibernate |
|---|---|---|
| SQL Writing | Manual | Automatic |
| Boilerplate | High | Low |
| Mapping | Manual | Automatic |
| Caching | No | Yes |
| Development Speed | Medium | Fast |
Hibernate vs Spring JDBC
| Feature | Spring JDBC | Hibernate |
|---|---|---|
| SQL Control | Full | Limited |
| Performance | Excellent | Good |
| CRUD Development | Medium | Excellent |
| ORM | No | Yes |
Interview Questions
What is Hibernate?
An ORM framework that maps Java objects to database tables.
What is ORM?
Object Relational Mapping.
Maps:
Objects
↔
Tables
What is SessionFactory?
Thread-safe factory for creating Sessions.
What is Session?
A database conversation and first-level cache container.
What is Persistence Context?
Entity tracking mechanism used by Hibernate.
What is Dirty Checking?
Automatic detection of modified entities.
What are Entity States?
Transient
Persistent
Detached
Removed
Difference Between Session and SessionFactory?
| Session | SessionFactory |
|---|---|
| Lightweight | Heavyweight |
| Not Thread Safe | Thread Safe |
| Per Request | Application Scope |
Key Takeaways
- Hibernate is the most popular ORM framework in Java.
- It maps Java Objects to Database Tables.
- SessionFactory creates Sessions.
- Session contains Persistence Context and First Level Cache.
- Dirty Checking automatically generates UPDATE statements.
- Hibernate internally uses JDBC.
- Understanding Hibernate Architecture is critical before learning JPA, Entity Lifecycle, Caching, and Performance Tuning.