
缓存有助于减少执行查询时的数据库网络调用。
一级缓存与会话链接。它是隐式实现的。一级缓存存在 直到会话对象存在为止。一旦会话对象终止/关闭,将会有 没有缓存对象。二级缓存适用于多个会话对象。它是链接的 与会话工厂。二级缓存对象可供所有会话使用 单会话工厂。当特定会话发生时,这些缓存对象将被终止 工厂已关闭。
实现二级缓存
我们需要添加以下依赖项才能使用二级缓存。
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 propertiestrue 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 获取缓存对象。










