Hibernate(14)什么是Hibernate的二级缓存?

Hibernate的二级缓存(Second-Level Cache)是超出Session范围的缓存,可以在多个Session之间共享。二级缓存用来存储那些在不同事务之间共享的数据,减少对数据库的访问,提高应用程序的性能。与一级缓存不同,二级缓存是可选的,需要显式配置和启用。

主要特点

  1. Session工厂范围内共享:二级缓存可以在多个Session之间共享数据。
  2. 可配置:需要显式配置缓存提供者和缓存策略。
  3. 缓存实体和集合:可以缓存实体、集合和查询结果。
  4. 持久性缓存:常用于缓存那些不经常修改的数据。

主要组件

  1. 缓存提供者:例如 Ehcache、Infinispan、Hazelcast 等。
  2. 缓存策略:配置缓存的使用策略,例如读写、只读等。

示例项目结构

为了深入理解二级缓存,下面是一个完整的示例,包括如何配置Hibernate文件、定义实体类、以及演示二级缓存的行为。

配置文件 hibernate.cfg.xml

假设使用Ehcache作为二级缓存提供者。

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.ehcache.EhCacheRegionFactory</property>
        <property name="hibernate.cache.use_query_cache">true</property>

        <!-- 映射类配置 -->
        <mapping class="com.example.domain.Student"/>
    </session-factory>
</hibernate-configuration>

Ehcache 配置文件 ehcache.xml

xml 复制代码
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"
         updateCheck="false">
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="300"
            timeToLiveSeconds="600"
            overflowToDisk="false"
            memoryStoreEvictionPolicy="LRU"/>
    <cache name="com.example.domain.Student"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>
</ehcache>

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;
    }
}

实体类 Student

java 复制代码
package com.example.domain;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    private int age;

    public Student() {}

    public Student(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;
    }
}

二级缓存示例代码

下面的示例展示了二级缓存的基本行为,包括如何在多个Session中共享缓存数据。

java 复制代码
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class HibernateSecondLevelCacheExample {
    public static void main(String[] args) {
        // 获取SessionFactory
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = null;
        Transaction transaction = null;

        // 向数据库添加一个测试对象
        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            Student student = new Student("John Doe", 20);
            session.save(student);

            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }

        // 第一次查询,发出SQL语句,并将数据放入二级缓存
        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            Student student = session.get(Student.class, 1L);
            System.out.println("First Query: " + student.getName() + ", Age: " + student.getAge());

            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }

        // 第二次查询,从二级缓存中读取数据,不发出SQL语句
        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            Student student = session.get(Student.class, 1L);
            System.out.println("Second Query: " + student.getName() + ", Age: " + student.getAge());

            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }

        // 关闭SessionFactory
        sessionFactory.close();
    }
}

详细解释

  1. 配置二级缓存 :在hibernate.cfg.xml中启用二级缓存,指定缓存提供者和缓存策略。

    xml 复制代码
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
    <property name="hibernate.cache.use_query_cache">true</property>
  2. 配置Ehcache :在ehcache.xml中配置缓存区域及其属性。

    xml 复制代码
    <cache name="com.example.domain.Student"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>
  3. 注解实体类 :使用@Cache注解和@CacheConcurrencyStrategy指定缓存策略。

    java 复制代码
    @Entity
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public class Student {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String name;
        private int age;
    }
  4. 第一次查询:在一个新的Session中查询实体,将数据放入二级缓存。

    java 复制代码
    Student student = session.get(Student.class, 1L);
  5. 第二次查询:在另一个新的Session中查询相同的实体,从二级缓存中读取数据,不发出SQL语句。

    java 复制代码
    Student student = session.get(Student.class, 1L);

事务管理

在进行数据库操作时,需要开启事务,并在操作完成后提交事务。如果操作失败,则回滚事务以确保数据一致性。

java 复制代码
Transaction transaction = session.beginTransaction();
try {
    // 持久化操作
    transaction.commit();
} catch (Exception e) {
    if (transaction != null) {
        transaction.rollback();
    }
    e.printStackTrace();
}

总结

Hibernate的二级缓存是超出Session范围的缓存,可以在多个Session之间共享数据。它通过减少数据库的访问次数,提高了应用程序的性能。

相关推荐
czlczl200209252 小时前
SpringBoot自动配置AutoConfiguration原理与实践
开发语言·spring boot·后端
heartbeat..3 小时前
Servlet 全面解析(JavaWeb 核心)
java·网络·后端·servlet
vx_bisheyuange3 小时前
基于SpringBoot的疗养院管理系统
java·spring boot·后端
京东零售技术3 小时前
2025京东零售技术年度精选 | 技术干货篇(内含福利)
前端·javascript·后端
布列瑟农的星空3 小时前
2025年度总结——认真生活,快乐工作
前端·后端
sunnyday04263 小时前
Spring Boot 项目中使用 Dynamic Datasource 实现多数据源管理
android·spring boot·后端
晴虹4 小时前
lecen:一个更好的开源可视化系统搭建项目--页面设计器(表单设计器)--全低代码|所见即所得|利用可视化设计器构建你的应用系统-做一个懂你的人
前端·后端·低代码
苏三的开发日记4 小时前
Hive的安装与配置
后端
小楼v4 小时前
一篇学会在IDEA中的Git常用操作及冲突的解决方法
git·后端