MyBatis 本身并不提供缓存机制,但你可以结合第三方缓存工具来实现缓存功能。在 MyBatis 中,你可以使用 Ehcache、Redis 等缓存工具来缓存查询结果。
以下是一个使用 Ehcache 的示例:
- 首先,将 Ehcache 依赖添加到你的项目中。如果你使用的是 Maven,可以在
pom.xml
文件中添加以下依赖:
org.mybatis mybatis-ehcache 3.5.7
- 在你的 MyBatis 配置文件(例如
mybatis-config.xml
)中,添加 Ehcache 的配置:
- 创建一个 Ehcache 配置文件(例如
ehcache.xml
),并将其放在类路径下(例如src/main/resources
):
- 在你的 Mapper 接口中,添加一个带有
@CacheNamespace
注解的方法:
import org.apache.ibatis.annotations.CacheNamespace; @CacheNamespace public interface MyMapper { MyEntity selectByPrimaryKey(Long id); }
现在,当你调用 selectByPrimaryKey
方法时,MyBatis 会自动使用 Ehcache 缓存查询结果。当相同的查询再次执行时,MyBatis 会直接从缓存中获取结果,而不是再次执行数据库查询。