Lecture 23: Level 2 Cache Using EHCache
Theory
Level 2 (L2) cache operates at the SessionFactory level, providing application-wide caching
capabilities that persist across different sessions.
Cache Hierarchy
● L1 Cache: Session-level (automatic)
● L2 Cache: SessionFactory-level (requires configuration)
Dependencies Setup
Required Dependencies in [Link]:
<dependency>
<groupId>[Link]</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-jcache</artifactId>
</dependency>
Configuration Implementation
[Link] Configuration:
xml
<hibernate-configuration xmlns="[Link]
<session-factory>
<!-- Database connection properties -->
<property name="[Link].driver_class">[Link]</property>
<property
name="[Link]">jdbc:postgresql://localhost:5432/telusko</property>
<property name="[Link]">postgres</property>
<property name="[Link]">5000</property>
<!-- Hibernate properties -->
<property name="[Link]">update</property>
<property
name="[Link]">[Link]</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- L2 Cache Configuration -->
<property name="[Link].use_second_level_cache">true</property>
<property
name="[Link].factory_class">[Link]
ctory</property>
<property
name="[Link]">[Link]</pr
operty>
</session-factory>
</hibernate-configuration>
Code Implementation
Modern Session Usage:
// Using modern find() method instead of deprecated get()
Laptop l1 = [Link]([Link], 2);
[Link](l1);
L2 Cache Benefits
Performance Advantages:
● Cross-Session Sharing: Data cached across multiple sessions
● Reduced Database Hits: Frequently accessed data served from cache
● Application-Level Optimization: Improves overall application performance
Cache Levels Comparison:
Feature L1 Cache L2 Cache
Scope Single Session SessionFactory-wide
Lifetime Session duration Application lifetime
Configuration Automatic Manual setup required
Sharing No sharing Shared across sessions
Provider Built-in Hibernate EHCache, Hazelcast, etc.
Implementation Steps:
1. Add Dependencies: Include ehcache and hibernate-jcache
2. Configure Properties: Enable L2 cache in [Link]
3. Entity Annotation: Add @Cache annotation to entities
4. Provider Setup: Configure cache provider (EHCache)
Cache Strategy Options:
● READ_ONLY: For immutable data
● READ_WRITE: For mutable data with read/write operations
● NONSTRICT_READ_WRITE: For rarely updated data
● TRANSACTIONAL: For transactional cache operations