温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java mybatis如何缓存

发布时间:2026-10-13 20:45:38 来源:亿速云 阅读:103 作者:小樊 栏目:编程语言

在 Java + MyBatis 中,缓存主要分为 一级缓存 和 二级缓存,下面用通俗的方式讲清楚原理和用法。


一、MyBatis 一级缓存(默认开启)

1. 是什么

  • SqlSession 级别的缓存
  • 同一个 SqlSession 内,执行相同的 SQL + 参数,会直接走缓存

2. 示例

SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);

User u1 = mapper.selectById(1); // 查数据库
User u2 = mapper.selectById(1); // 走一级缓存

3. 什么时候失效

一级缓存会在以下情况清空:

  • 执行了 insert / update / delete
  • 手动调用 session.clearCache()
  • 不是同一个 SqlSession

✅ 一级缓存无法关闭(只能避免)


二、MyBatis 二级缓存(Mapper 级别)

1. 是什么

  • Mapper(namespace)级别
  • 多个 SqlSession 可共享
  • 需要手动开启

2. 开启步骤

(1)全局开启(默认就是 true)

<settings>
    <setting name="cacheEnabled" value="true"/>
</settings>

(2)在 Mapper 中开启缓存

<mapper namespace="com.xxx.mapper.UserMapper">
    <cache/>
</mapper>

或注解方式(MyBatis 3.4+ 支持有限):

@CacheNamespace
public interface UserMapper {
}

(3)实体类序列化

public class User implements Serializable {
}

3. 示例

SqlSession s1 = factory.openSession();
UserMapper m1 = s1.getMapper(UserMapper.class);
m1.selectById(1); // 查库
s1.close();

SqlSession s2 = factory.openSession();
UserMapper m2 = s2.getMapper(UserMapper.class);
m2.selectById(1); // 走二级缓存

三、二级缓存配置项

<cache
    eviction="LRU"
    flushInterval="60000"
    size="512"
    readOnly="true"/>

含义:

  • eviction:回收策略(LRU / FIFO)
  • flushInterval:刷新时间(毫秒)
  • size:缓存对象数量
  • readOnly:是否只读

四、和 Spring / Spring Boot 整合注意

1. Spring 中一级缓存基本“没用”

  • 每个 Mapper 方法结束后 SqlSession 就关闭
  • 一级缓存立即失效

2. 二级缓存要谨慎

  • 分布式环境 ❌(需用 Redis)
  • 多表关联更新 ❌(容易脏数据)

五、企业级推荐方案(重要)

✅ MyBatis 缓存 ≠ 业务缓存

实际项目常用:

  • MyBatis:关闭或仅一级
  • 业务缓存:
    • Redis
    • Spring Cache(@Cacheable)
@Cacheable("user")
public User getUserById(Integer id) {
    return userMapper.selectById(id);
}

六、总结一句话

缓存 级别 是否默认 使用场景
一级缓存 SqlSession ✅ 单次请求内部
二级缓存 Mapper ❌ 单应用读多写少
Redis 应用级 ❌ 分布式、生产推荐

如果你用的是 Spring Boot / MyBatis-Plus / Redis 整合缓存,我可以给你具体代码示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手