温馨提示×

温馨提示×

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

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

java mybatis怎么懒加载

发布时间:2026-09-23 07:57:36 来源:亿速云 阅读:94 作者:小樊 栏目:编程语言

在 MyBatis 中,“懒加载(Lazy Loading)”通常指的是 关联对象(association / collection)的延迟加载,也就是:用到的时候才去查数据库。

下面从 配置方式 和 使用示例 两部分说明。


一、开启全局懒加载(推荐)

在 mybatis-config.xml 中配置:

<settings>
    <!-- 开启延迟加载 -->
    <setting name="lazyLoadingEnabled" value="true"/>
    <!-- 关闭积极加载(按需加载) -->
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>

说明:

  • lazyLoadingEnabled=true:支持懒加载
  • aggressiveLazyLoading=false:只有真正调用关联对象时才加载(否则会在主对象加载时就加载所有关联)

二、在映射文件中使用 fetchType

1️⃣ 一对一(association)

<resultMap id="userMap" type="User">
    <id property="id" column="id"/>
    <result property="name" column="name"/>

    <!-- 懒加载 -->
    <association property="card"
                 column="id"
                 select="selectCardByUserId"
                 fetchType="lazy"/>
</resultMap>

<select id="selectUserById" resultMap="userMap">
    select * from user where id = #{id}
</select>

<select id="selectCardByUserId" resultType="Card">
    select * from card where user_id = #{id}
</select>

✅ 只有当你调用 user.getCard() 时,才会执行 selectCardByUserId


2️⃣ 一对多(collection)

<resultMap id="deptMap" type="Dept">
    <id property="id" column="id"/>
    <result property="name" column="name"/>

    <collection property="users"
                column="id"
                select="selectUsersByDeptId"
                fetchType="lazy"/>
</resultMap>

<select id="selectDeptById" resultMap="deptMap">
    select * from dept where id = #{id}
</select>

<select id="selectUsersByDeptId" resultType="User">
    select * from user where dept_id = #{id}
</select>

三、注意点(非常重要)

✅ 1. 必须使用 Session 未关闭 的情况

懒加载依赖 SqlSession:

  • 在 Spring + MyBatis 中:
    • 事务方法内 ✅
    • Controller 直接返回对象 ❌(session 已关闭,会报错)

Spring 场景下推荐:

@Transactional
public User getUser(int id) {
    return userMapper.selectUserById(id);
}

✅ 2. 序列化问题(JSON 返回)

如果直接把懒加载对象转 JSON:

  • 可能触发加载
  • 或抛 LazyInitializationException

解决方案:

  • DTO 转换
  • @JsonIgnore 忽略关联字段

✅ 3. 与 fetchType="eager" 的区别

fetchType 行为
lazy 用到才查
eager 立即查

四、Spring Boot 中的配置示例

mybatis:
  configuration:
    lazy-loading-enabled: true
    aggressive-lazy-loading: false

五、适用场景总结

✅ 适合:

  • 关联数据不常用
  • 列表查询性能优化

❌ 不适合:

  • 必定使用关联数据
  • 批量查询(N+1 问题)

如果你用的是 MyBatis-Plus / Spring Boot / 具体实体结构,我可以给你更贴合的示例。

向AI问一下细节

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

AI
助
手