延迟加载:
在做联合查询是查出首层实体对象,具体实体对象内部的关联对象只有用到的时候才去查询使用。
首先在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>
个人学习笔记
本文详细介绍了MyBatis中的延迟加载配置与实现方法,包括一对多、多对一及一对一的延迟加载策略,通过具体的XML配置示例,展示了如何在联合查询中仅加载首层实体对象,关联对象则在需要时按需加载,有效提高了数据查询效率。
364

被折叠的 条评论
为什么被折叠?



