MyBatis框架本身并未内置缓存机制,但这并不意味着它与缓存无缘。事实上,MyBatis将缓存功能完全开放给了第三方集成方案。简单来说,无论你选用Ehcache、Redis还是其他缓存工具,只要配置得当,查询结果就能被有效缓存,实现性能的显著提升。

下面以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的专属配置文件ehcache.xml,并将其放置在类路径下(通常为src/main/resources)。该文件用于定义默认缓存策略,以及针对特定Mapper方法的个性化缓存参数:
<ehcache xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://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接口上添加@CacheNamespace注解,告知MyBatis该Mapper中的所有查询操作将启用缓存:
import org.apache.ibatis.annotations.CacheNamespace;@CacheNamespacepublic interface MyMapper {MyEntity selectByPrimaryKey(Long id);}
完成上述步骤后,调用selectByPrimaryKey方法时,MyBatis将自动使用Ehcache缓存。首次查询从数据库读取数据并写入缓存;后续相同查询将直接命中缓存,无需访问数据库——这是提升响应速度的实用方案。
