MyBatis提供了二级缓存(Second Level Cache)来提高查询性能。二级缓存是一个跨 Session 的缓存,可以在多个 Session 之间共享缓存数据。以下是MyBatis二级缓存的实现步骤:
-
配置文件设置: 在MyBatis配置文件(例如
mybatis-config.xml)中开启二级缓存:<!-- mybatis-config.xml --> <configuration> <!-- 其他配置 --> <settings> <setting name="cacheEnabled" value="true"/> </settings> </configuration> -
映射文件设置: 在需要使用二级缓存的映射文件(Mapper XML文件)中配置缓存:
<!-- userMapper.xml --> <mapper namespace="com.example.UserMapper"> <!-- 缓存配置 --> <cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/> <!-- 其他映射配置 --> <select id="getUserById" resultType="User" useCache="true"> SELECT * FROM users WHERE id = #{id} </select> </mapper>eviction:指定缓存的清理策略,常用的有LRU(Least Recently Used,最近最少使用)。flushInterval:刷新缓存间隔,单位为毫秒,表示缓存每隔多少时间刷新一次。size:缓存的最大数量,当缓存达到最大数量时,会按照清理策略清理部分缓存。readOnly:标志缓存是否只读,如果设置为true,则表示缓存数据不会被修改。
-
实体类设置: 实体类需要实现
Serializable接口,以支持对象的序列化,以便可以缓存对象。public class User implements Serializable { // 类定义 } -
使用Cache标签自定义缓存: 你也可以使用
<cache>标签来自定义二级缓存的实现。例如,使用Ehcache作为二级缓存:<!-- mybatis-config.xml --> <configuration> <!-- 其他配置 --> <settings> <!-- 关闭MyBatis的默认二级缓存 --> <setting name="cacheEnabled" value="false"/> </settings> <!-- 自定义二级缓存实现 --> <typeAliases> <!-- 自定义Cache实现类 --> <typeAlias alias="Ehcache" type="org.mybatis.caches.ehcache.EhcacheCache"/> </typeAliases> <!-- 使用自定义Cache实现二级缓存 --> <environments default="development"> <environment id="development"> <!-- 配置数据源 --> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <!-- 配置数据源相关信息 --> </dataSource> <!-- 使用Ehcache作为二级缓存 --> <cache type="Ehcache"/> </environment> </environments> </configuration>
通过以上配置,MyBatis就会使用配置的二级缓存来提高查询性能。二级缓存是跨Session的,因此在不同的Session中可以共享缓存数据。在进行更新、插入、删除等写操作时,会自动刷新缓存,以保持数据一致性。