在 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<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
<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>
懒加载依赖 SqlSession:
Spring 场景下推荐:
@Transactional
public User getUser(int id) {
return userMapper.selectUserById(id);
}
如果直接把懒加载对象转 JSON:
LazyInitializationException解决方案:
@JsonIgnore 忽略关联字段fetchType="eager" 的区别| fetchType | 行为 |
|---|---|
| lazy | 用到才查 |
| eager | 立即查 |
mybatis:
configuration:
lazy-loading-enabled: true
aggressive-lazy-loading: false
✅ 适合:
❌ 不适合:
如果你用的是 MyBatis-Plus / Spring Boot / 具体实体结构,我可以给你更贴合的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。