mybatis hive能否实现缓存机制
作者:技术拾光时间:2026-06-28 08:44:10浏览:663
MyBatis本身无内置缓存,但可集成Ehcache等第三方工具。添加依赖、配置XML、在Mapper接口加@CacheNamespace注解即可启用二级缓存。首次查询后结果存入缓存,后续相同查询直接从缓存读取,可极大提升响应速度,尤其适合读多写少场景,能有效降低数据库压力。
MyBatis 框架本身没有内置缓存,但这一框架将缓存能力完全开放给第三方实现。开发者可以选择 Ehcache、Redis 或其他缓存工具,只要正确接入,查询结果就能稳定存入缓存,从而显著提升性能。

MyBatis 整合 Ehcache 缓存实现步骤
下面以 Ehcache 为例,详细介绍接入流程,步骤清晰直观。
第一步:添加 Ehcache 依赖
在 Maven 项目的 pom.xml 文件中加入以下依赖:
<dependency><groupId>org.mybatisgroupId><artifactId>mybatis-ehcacheartifactId><version>3.5.7version>dependency>
第二步:在 MyBatis 核心配置文件中启用缓存
在 mybatis-config.xml 中开启缓存开关,并配置懒加载、自动映射等常用设置。以下配置片段可作为“开箱即用”模板:
<configuration><settings><setting name="cacheEnabled" value="true"/><setting name="lazyLoadingEnabled" value="true"/><setting name="multipleResultSetsEnabled" value="true"/><setting name="useColumnLabel" value="true"/><setting name="autoMappingBeha vior" value="PARTIAL"/><setting name="defaultExecutorType" value="SIMPLE"/><setting name="defaultStatementTimeout" value="25"/><setting name="defaultFetchSize" value="100"/><setting name="useCursorFetch" value="false"/><setting name="useGeneratedKeys" value="false"/><setting name="autoMappingUnknownColumnToBean" value="true"/><setting name="defaultCacheScope" value="SESSION"/>settings>configuration>
第三步:创建 Ehcache 配置文件
在类路径(通常为 src/main/resources)下创建 ehcache.xml,定义默认缓存策略以及针对特定 Mapper 方法的个性化参数:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd" updateCheck="false"><diskStore path="ja va.io.tmpdir/ehcache"/><defaultCachemaxElementsInMemory="100"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true"maxElementsOnDisk="10000000"diskPersistent="true"diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"/><cache name="com.example.MyMapper.selectByPrimaryKey" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" diskPersistent="true" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>ehcache>
第四步:在 Mapper 接口上添加缓存注解
在对应的 Mapper 接口上使用 @CacheNamespace 注解,告知 MyBatis 该 Mapper 的查询需要启用缓存:
import org.apache.ibatis.annotations.CacheNamespace;@CacheNamespacepublic interface MyMapper {MyEntity selectByPrimaryKey(Long id);}
完成上述配置后,调用 selectByPrimaryKey 方法时,MyBatis 将自动走 Ehcache 缓存。第一次查询从数据库读取,结果写入缓存;后续相同查询直接命中缓存,不再访问数据库——这是提升响应速度的务实做法。
