You need to enable JavaScript to run this app. Spring Boot2.x下如何为第三方Jar中的Hibernate实体配置EhCache二级缓存
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot2.x下如何为第三方Jar中的Hibernate实体配置EhCache二级缓存

Spring Boot 2.x 基于XML为第三方Jar实体配置Hibernate二级缓存(EhCache 2.x实现)

适配技术栈:Hibernate 5.x+、EhCache 2.x+、Spring Boot 2.x+,无需修改第三方Jar内实体源码,无需使用@Cacheable/@Cache注解。


1. 引入核心依赖

在pom.xml中添加如下依赖,注意Hibernate适配包版本需与Spring Boot自带Hibernate版本对齐:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Hibernate EhCache适配包 -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-ehcache</artifactId>
    <version>5.6.14.Final</version>
</dependency>
<!-- EhCache 2.x核心包 -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.9.2</version>
</dependency>

2. 编写EhCache缓存规则配置

在resources目录下新建ehcache.xml,为每个需要缓存的第三方实体单独配置缓存规则,cache标签的name属性必须对应第三方实体的全限定类名:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!-- 默认缓存配置,未单独配置的实体将使用该规则 -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="3600"
            timeToLiveSeconds="7200"
            overflowToDisk="false"
            diskPersistent="false"/>

    <!-- 第三方实体专属缓存配置,示例如下 -->
    <cache name="com.third.part.entity.User"
           maxElementsInMemory="2000"
           eternal="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="3600"
           overflowToDisk="false"/>
    <cache name="com.third.part.entity.Order"
           maxElementsInMemory="5000"
           eternal="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="3600"
           overflowToDisk="false"/>
</ehcache>

3. 调整Spring Boot核心配置

在application.yml中开启Hibernate二级缓存,指定缓存实现和映射文件扫描路径:

spring:
  jpa:
    properties:
      hibernate:
        # 开启二级缓存
        cache:
          use_second_level_cache: true
          use_query_cache: false
          region:
            factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
          # 指定EhCache配置文件路径
          ehcache:
            configuration_resource_name: ehcache.xml
        # 扫描自定义HBM映射文件路径,缓存规则将放在该目录下
        mapping:
          locations: classpath:hibernate/mapping/*.hbm.xml

4. 编写第三方实体缓存映射文件

在resources/hibernate/mapping目录下新建third-entity-cache.hbm.xml,无需编写实体字段映射,仅声明缓存规则即可,Hibernate会自动和已扫描到的第三方实体关联:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- package属性填第三方实体所在的包名 -->
<hibernate-mapping package="com.third.part.entity">
    <!-- 只读实体配置示例:比如字典类数据不会修改,用read-only性能更高 -->
    <class name="User" mutable="false">
        <cache usage="read-only" include="all"/>
    </class>
    <!-- 可修改实体配置示例:需要更新缓存的实体用read-write -->
    <class name="Order" mutable="true">
        <cache usage="read-write" include="all"/>
    </class>
    <!-- 更多第三方实体按以上格式依次添加即可 -->
</hibernate-mapping>

5. 注册EhCacheManager到Spring容器

如果需要在业务代码中手动操作缓存,可添加如下配置类将EhCacheManager注册为Spring Bean:

import net.sf.ehcache.CacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class EhCacheConfig {

    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
        factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        factoryBean.setShared(true);
        return factoryBean;
    }

    @Bean
    public CacheManager ehCacheManager(EhCacheManagerFactoryBean factoryBean) {
        return factoryBean.getObject();
    }
}

6. 配置验证

  • 开启Hibernate SQL日志:配置spring.jpa.show-sql=true,重复查询同一个第三方实体,仅第一次会打印SQL语句,后续查询无SQL输出说明缓存生效
  • 注入CacheManager调用getCacheNames()方法,可看到所有配置的第三方实体对应的缓存名称

内容的提问来源于stack exchange,提问作者radhik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 21:06:03