mybatis:一对多延迟加载

本文详细介绍了MyBatis中的延迟加载配置与实现方法,包括一对多、多对一及一对一的延迟加载策略,通过具体的XML配置示例,展示了如何在联合查询中仅加载首层实体对象,关联对象则在需要时按需加载,有效提高了数据查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

延迟加载:

在做联合查询是查出首层实体对象,具体实体对象内部的关联对象只有用到的时候才去查询使用。

首先在mybatis核心配置文件中配置:

lazyLoadingEnabled:true使用延迟加载,false禁用延迟加载。默认为true

aggressiveLazyLoading:true启用时不使用延迟加载,false使用延迟加载

<settings>
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>

一对多延迟加载:

需要两条sql语句配合使用

第一步配置resultMap

Collection:是person内部的集合,

select:延迟加载的sql语句

column:延迟加载sql语句的查询条件的列

<resultMap type="cn.itcast.model.Person" id="personLazyRM" extends="personRM">
	<collection property="ordersList" column="person_id" select="mybatis.sqlMap.OrdersMapper.selectOrderByPersonId">
	</collection>
</resultMap>

查询语句:

<select id="selectForLazy" parameterType="int" resultMap="personLazyRM">
    select * from person p where p.person_id = #{personId}
</select>

延迟加载的查询语句

<select id="selectOrderByPersonId" parameterType="int" resultMap="BaseResultMap">
  	select * from orders o where  o.person_id = #{personId}
 </select>

多对一或一对一的延迟加载

ResultMap
<resultMap type="cn.itcast.model.Orders" id="lazyRM" extends="BaseResultMap">
  	<association property="person" column="order_id" select="cn.itcast.model.Person.selectPersonByOrderId">
    </association>
</resultMap>

查询语句
<select id="selectByPrimaryKeyForLazy" resultMap="lazyRM" parameterType="java.lang.Integer" >
    select  * from orders where order_id = #{orderId}
</select>
延迟加载的查询语句
<select id="selectPersonByOrderId" parameterType="int" resultMap="personRM">
		select p.* from person p, orders o where p.person_id = o.person_id and o.order_id = #{orderId}
</select>

个人学习笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值