Hibernate二级缓存是如何工作的?

2023年 9月 14日 26.2k 0

Hibernate二级缓存是如何工作的?

缓存有助于减少执行查询时的数据库网络调用。

一级缓存与会话链接。它是隐式实现的。一级缓存存在
直到会话对象存在为止。一旦会话对象终止/关闭,将会有
没有缓存对象。二级缓存适用于多个会话对象。它是链接的
与会话工厂。二级缓存对象可供所有会话使用
单会话工厂。当特定会话发生时,这些缓存对象将被终止
工厂已关闭。

实现二级缓存

我们需要添加以下依赖项才能使用二级缓存。

net.sf.ehcache
ehcache
2.10.9.2

org.hibernate
hibernate-ehcache
5.4.32.Final

登录后复制

注意- hibernate ehcache 版本号必须与 hibernate 版本号相同。

现在,我们需要添加 hibernate 配置文件,这将使 hibernate 能够连接到
提供的数据库并使用二级缓存。

com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/demo?useSSL=false
root
root

4

true
//caching properties
true
org.hibernate.cache.ehcache.EhCacheRegionFactory

org.hibernate.dialect.MySQL5Dialect

create-drop

登录后复制

示例

默认情况下,java 中的所有实体都是不缓存的。因此,为了启用实体的缓存,我们在实体类 Parent 中使用 @Cacheable 和 @Cache 注释 -

import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;

@Entity
@Table( name = " Employee")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
@Column(name = "first_name")
String firstName;
@Column(name = "last_name")
String lastName;
}
Now, let’s check whether second level cache works:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration()
.configure("academy/company/hibernate.cfg.xml")
.buildSessionFactory();
Session session1 = sessionFactory.openSession();
Parent parent1 = session1.get(Parent.class, 4);
System.out.println(parent1.id + " " + parent1.firstName + " " + parent1.lastName);
session1.close();

Session session2 = sessionFactory.openSession();
Parent parent2 = session2.get(Parent.class, 4);
System.out.println(parent2.id + " " + parent2.firstName + " " + parent2.lastName);
session2.close();
}
}

登录后复制

输出

Hibernate: select parent0.id as id1, parent0.first_name as first_name1, parent0.last_name as last_name1 from Parent parent0 where parent0.id=?
1 Subash Chopra
1 Subash Chopra

登录后复制

从控制台我们可以清楚地看到hibernate在session1期间只执行了一次查询。现在,当 session2 访问相同的查询时,它不会对数据库进行网络调用来执行它。相反,由于我们使用二级缓存,它将从 session1 获取缓存对象。

以上就是Hibernate二级缓存是如何工作的?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论