0% found this document useful (0 votes)
67 views

Unit06 Hibernate Caching

Uploaded by

Long Trần
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Unit06 Hibernate Caching

Uploaded by

Long Trần
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Hibernate Caching

Design by: DieuNT1

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher


1
Academy - Internal Use
Lesson Objectives
• Understand the type of cache levels in Hibernate.
1

• Able to implement First Level Cache


2

• Know how to configure using Cache Level 2.


3

• Able to implement Query Cache.


4

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 2


Agenda
vIntroduction to Caching in Hibernate
vFirst Level Cache
vSecond Level Cache
vQuery Cache

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 3


Section 01

CACHING IN HIBERNATE

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 4


Introduction
v Hibernate Cache can be very useful in gaining fast
application performance if used correctly.
v Reduce the number of database queries, hence reducing
the throughput time of the application.
v Hibernate comes with different types of Cache:
§ First Level Cache
§ Second Level Cache
§ Query Cache

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 5


First Level Cache
v Hibernate first level cache is associated with the Session
object.
v Hibernate first level cache is enabled by default and there is
no way to disable it.
v Any object cached in a session will not be visible to other
sessions and when the session is closed, all the cached
objects will also be lost.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 6


First Level Cache
v Hibernate provides methods through which we can delete
selected objects from the cache or clear the cache
completely.
§ evict() remove a single object from the hibernate first level cache.
§ clear() clear the cache: delete all the objects from the cache.
§ contains() check if an object is present in the hibernate cache or not

Session session = HibernateUtil.getSessionFactory().openSession();



AntEntity entity = (AntEntity) session.load(AntEntity.class,
new Integer(1));
entity = (AntEntity) session.load(AntEntity.class, new Integer(1));

session.evict(entity); //session.clear();

entity = (AntEntity) session.load(AntEntity.class, new Integer(1));


43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 7


First Level Cache
v Example 1: load the entity many times in the same session
session = HibernateUtils.getSessionFactory().openSession();

Departments department = session.load(Departments.class, new Integer(1));


System.out.println(department.getDeptName());

// Lấy đối tượng department thêm lần nữa


department = (Departments) session.load(Departments.class, new Integer(1));
System.out.println(department.getDeptName());

// Lấy thêm nhiều lần nữa


for (int i = 0; i < 5; i++) {
department = (Departments) session.load(Departments.class,
new Integer(1));
System.out.println(department.getDeptName());
}
43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 8
First Level Cache
v Example 1: load the entity many times in the same session

Console log:

Hibernate: select department0_.dept_id as dept_id1_6_0_,


department0_.dept_name as dept_nam2_6_0_ from dbo.Departments
department0_ where department0_.dept_id=?
IT Tools
IT Tools
IT Tools
IT Tools
IT Tools
IT Tools
IT Tools

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 9


First Level Cache
v Example 2: load the entity many times in the different session
sessionA = HibernateUtils.getSessionFactory().openSession();
sessionB = HibernateUtils.getSessionFactory().openSession();

Departments department = sessionA.load(Departments.class,


new Integer(1));
System.out.println(department.getDeptName());

// Lấy đối tượng department thêm lần nữa trong sesssionA


department = sessionA.load(Departments.class, new Integer(1));
System.out.println(department.getDeptName());

// Lấy đối tượng department thêm lần nữa trong sessionB


department = (Departments) sessionB.load(Departments.class,
new Integer(1));
System.out.println(department.getDeptName());

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 10


First Level Cache
v Example 2: load the entity many times in the same session

Console log:

Hibernate: select department0_.dept_id as dept_id1_6_0_,


department0_.dept_name as dept_nam2_6_0_ from dbo.Departments
department0_ where department0_.dept_id=?
IT Tools
IT Tools
Hibernate: select department0_.dept_id as dept_id1_6_0_,
department0_.dept_name as dept_nam2_6_0_ from dbo.Departments
department0_ where department0_.dept_id=?
IT Tools

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 11


First Level Cache
v Example 3: remove all of the objects from the cache
session = HibernateUtils.getSessionFactory().openSession();

// Lấy đối tượng department lần đầu tiên


Departments department = session.load(Departments.class,
new Integer(1));
System.out.println(department.getDeptName());

// Lấy tiếp lần thứ 2


department = session.load(Departments.class, new Integer(1));
System.out.println(department.getDeptName());
// Xóa bỏ khỏi session - hay First Level Cache
session.evict(department);
// session.clear();

// Lấy tiếp đối tượng department lần nữa


department = (Departments) session.load(Departments.class,
new Integer(1));
System.out.println(department.getDeptName());

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 12


First Level Cache
v Example 3: load the entity many times in the same session

Console log:

Hibernate: select department0_.dept_id as dept_id1_6_0_,


department0_.dept_name as dept_nam2_6_0_ from dbo.Departments
department0_ where department0_.dept_id=?
IT Tools
IT Tools
Hibernate: select department0_.dept_id as dept_id1_6_0_,
department0_.dept_name as dept_nam2_6_0_ from dbo.Departments
department0_ where department0_.dept_id=?
IT Tools

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 13


Section 02

SECOND LEVEL CACHE

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 14


Second Level Cache
v First Level Cache is a session scoped cache which ensures that each
entity instance is loaded only once in the persistent context.
v Once the session is closed, first-level cache is terminated as well. This is
actually desirable, as it allows for concurrent sessions to work with entity
instances in isolation from each other.
v Second-level cache is SessionFactory-scoped, meaning it is shared by
all sessions created with the same session factory.
v When an entity instance is looked up by its id, and if second-level
caching is enabled for that entity, the following happens:
P If an instance is already present in the first-level cache, it is returned from there
P If an instance is not found in the first-level cache, and the corresponding instance state
is cached in the second-level cache, then the data is fetched from there and an
instance is assembled and returned
P Otherwise, the necessary data are loaded from the database and an instance is
assembled and returned.

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 15


Second Level Cache
v Hibernate second-level caching is designed to be unaware[không
biết] of the actual cache provider used.

v Hibernate only needs to be provided with an implementation of


the org.hibernate.cache.spi.RegionFactory interface which
encapsulates all details specific to actual cache providers.
v It acts as a bridge between Hibernate and cache providers.
v Hibernate Second Level cache providers include EHCache and
Infinispan. Use Ehcache as a cache provider:

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 16


Second Level Cache
v We add the Ehcache region factory implementation to the
classpath with the following Maven dependency:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.4.12.Final</version>
</dependency>

<!-- Ehcache -->


<!-- https://mvnrepository.com/artifact/
net.sf.ehcache/ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.5</version>
</dependency>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 17


Second Level Cache
vTo L2 caching is enabled and we give it the name of
the region factory class.
vhibernate.cfg.xml:
<property name="hibernate.cache.use_second_level_cache“
value="true" />
<property name="hibernate.cache.region.factory_class"
value="org.hibernate.cache.ehcache.EhCacheRegionFactory" />

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 18


Making an Entity Cacheable
v Entity
@Entity
@Table(name = "Departments", schema = "dbo")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Departments {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "dept_id")
private int deptId;

@Column(name = "dept_name")
private String deptName;

@OneToMany(mappedBy = "department", fetch = FetchType.LAZY)


private Set<Employees> employees;

// getter and setter methods


}

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 19


Cache Concurrency Strategy
v READ_ONLY: Used only for entities that never change (exception is thrown if an
attempt to update such an entity is made). It is very simple and performant. Very
suitable for some static reference data that don't change
v NONSTRICT_READ_WRITE: Cache is updated after a transaction that changed
the affected data has been committed. Thus, strong consistency is not
guaranteed and there is a small time window in which stale data may be
obtained from cache. This kind of strategy is suitable for use cases that can
tolerate eventual consistency
v READ_WRITE: This strategy guarantees strong consistency which it achieves
by using ‘soft' locks: When a cached entity is updated, a soft lock is stored in the
cache for that entity as well, which is released after the transaction is committed.
All concurrent transactions that access soft-locked entries will fetch the
corresponding data directly from database
v TRANSACTIONAL: Cache changes are done in distributed XA transactions. A
change in a cached entity is either committed or rolled back in both database
and cache in the same XA transaction

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 20


Cache Management
v If expiration and eviction policies are not defined, the cache could grow
indefinitely and eventually consume all of available memory.
v In most cases, Hibernate leaves cache management duties like these to
cache providers, as they are indeed specific to each cache
implementation.
v For example, we could define the following Ehcache configuration to limit
the maximum number of cached Departments instances to 1000:

<ehcache>
<cache name="fa.training.entities.Departments"
maxElementsInMemory="1000" />
</ehcache>

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 21


Second Level Cache
v Example:
try {
sessionA = HibernateUtils.getSessionFactory().openSession();
sessionB = HibernateUtils.getSessionFactory().openSession();

Departments department = sessionA.load(Departments.class, deptId);


System.out.println(department.getDeptName());

// Lấy đối tượng department thêm lần nữa trong sesssionA


department = sessionA.load(Departments.class, deptId);
System.out.println(department.getDeptName());

// Lấy đối tượng department thêm lần nữa trong sessionB


department = (Departments) sessionB.load(Departments.class, deptId);
System.out.println(department.getDeptName());

} finally {
if (sessionA != null) {
sessionA.close();
}
if (sessionB != null) {
sessionB.close();
}
}

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 22


Second Level Cache
v Console log:
Hibernate: select department0_.dept_id as dept_id1_6_0_,
department0_.dept_name as dept_nam2_6_0_ from dbo.Departments
department0_ where department0_.dept_id=?
IT Tools
IT Tools
IT Tools

v Remove all of the objects from cache level 2:


sessionFactory.getCache().evictEntity(User.class, user);
sessionFactory.getCache().evictAllRegions()

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 23


Section 03

QUERY CACHE

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 24


Query Cache
v Aside from caching entities and collections, Hibernate offers
a query cache too. This is useful for frequently executed
queries with fixed parameter values.
§ To use query caching, you will first need to enable it with the
following configuration property:

<property name="hibernate.cache.use_query_cache" value="true" />

§ Caching query using Hibernate native API

List<Person> persons = session.createQuery( "select p " + "from Person p " +


"where p.name = :name") .setParameter( "name", "John Doe")
.setCacheable(true) .list();

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 25


Query Cache
v Hibernate defined the CacheMode enumeration to describe
the ways of interactions with the cached
CacheMode Description
CacheMode.NORMAL Default. Reads/writes data from/into the cache

CacheMode.REFRESH Doesn’t read from cache, but writes to the cache upon loading from
the database

CacheMode.PUT Doesn’t read from cache, but writes to the cache as it reads from
the database

CacheMode.GET Read from the cache, but doesn’t write to cache

CacheMode.IGNORE Doesn’t read/write data from/into the cache

List<Person> persons = session.createQuery( "select p from Person p" )


.setCacheable( true ) .setCacheMode(CacheMode.REFRESH) .list();

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 26


Summary
vIntroduction to Caching in Hibernate
vFirst Level Cache
vSecond Level Cache
vQuery Cache

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher Academy - Internal Use 27


Thank you

43e-BM/HR/HDCV/FSOFT V1.2 - ©FPT SOFTWARE - Fresher


28
28
Academy - Internal Use

You might also like