Hibernate的Caching Provider
在Hibernate中,缓存(Caching)是提高应用程序性能的重要机制。缓存可以减少对数据库的访问次数,从而降低数据库的负载和延迟。Hibernate支持两级缓存机制:
- 一级缓存(First Level Cache):Session级别的缓存,默认启用且不可关闭。
- 二级缓存(Second Level Cache):SessionFactory级别的缓存,需要显式配置和开启。
为了使用二级缓存,必须配置一个缓存提供者(Caching Provider)。常见的缓存提供者包括:
- EHCache
- Infinispan
- OSCache
- Hazelcast
配置EHCache作为Hibernate的缓存提供者
步骤
- 添加依赖:在项目的依赖管理文件中添加EHCache和Hibernate的相关依赖。
- 配置
hibernate.cfg.xml文件:添加缓存相关的配置。 - 配置EHCache的缓存配置文件
ehcache.xml。 - 在实体类中配置缓存注解。
示例代码
添加Maven依赖
在pom.xml文件中添加以下依赖:
xml
<dependencies>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.32.Final</version>
</dependency>
<!-- Hibernate EHCache -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.4.32.Final</version>
</dependency>
<!-- EHCache Core -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.9.1</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
配置文件 hibernate.cfg.xml
xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接配置 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<!-- Hibernate 属性配置 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 二级缓存配置 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.jcache.JCacheRegionFactory</property>
<property name="hibernate.javax.cache.provider">org.ehcache.jsr107.EhcacheCachingProvider</property>
<property name="hibernate.javax.cache.uri">/ehcache.xml</property>
<!-- 映射类 -->
<mapping class="com.example.domain.Person"/>
</session-factory>
</hibernate-configuration>
EHCache配置文件 ehcache.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache:config
xmlns:ehcache="http://www.ehcache.org/v3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">
<cache alias="com.example.domain.Person">
<expiry>
<ttl unit="minutes">10</ttl>
</expiry>
<resources>
<heap unit="entries">1000</heap>
<offheap unit="MB">10</offheap>
</resources>
</cache>
</ehcache:config>
实体类 Person
在实体类中使用缓存注解。
java
package com.example.domain;
import javax.persistence.*;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Table(name = "person")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private int age;
public Person() {}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getters 和 setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
使用Hibernate进行CRUD操作
HibernateUtil类
java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// 从配置文件创建SessionFactory
sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable ex) {
// 记录启动失败的错误
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
CRUD操作类
java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class HibernateCRUDExample {
public static void main(String[] args) {
// 获取SessionFactory
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
// 插入数据
insertPerson(sessionFactory);
// 查询数据
queryPerson(sessionFactory);
// 更新数据
updatePerson(sessionFactory);
// 删除数据
deletePerson(sessionFactory);
// 关闭SessionFactory
sessionFactory.close();
}
private static void insertPerson(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try {
Person person = new Person("John Doe", 30);
session.save(person);
transaction.commit();
System.out.println("Inserted Person: " + person.getName());
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
private static void queryPerson(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
try {
Person person = session.get(Person.class, 1L);
if (person != null) {
System.out.println("Queried Person: " + person.getName() + ", Age: " + person.getAge());
} else {
System.out.println("No Person found with ID 1");
}
} finally {
if (session != null) {
session.close();
}
}
}
private static void updatePerson(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try {
Person person = session.get(Person.class, 1L);
if (person != null) {
person.setName("Jane Doe");
person.setAge(25);
session.update(person);
transaction.commit();
System.out.println("Updated Person: " + person.getName() + ", Age: " + person.getAge());
} else {
System.out.println("No Person found with ID 1");
}
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
private static void deletePerson(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try {
Person person = session.get(Person.class, 1L);
if (person != null) {
session.delete(person);
transaction.commit();
System.out.println("Deleted Person: " + person.getName());
} else {
System.out.println("No Person found with ID 1");
}
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
}