mybatis延迟加载

1.首先在核心配置文件:sqlMapConfig.xml  中开启延迟加载

开启延迟加载的配置, settings放在最上面
<settings>
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
		<!-- 开启二级缓存 -->
		<setting name="cacheEnabled" value="true"/>
</settings>
说明:
	lazyLoadingEnabled:延迟加载总开关
	aggressiveLazyLoading:
	cacheEnabled:二级缓存开关

2.一对多延迟加载:

1.映射文件PersonMapper.xml中新增:resultMap并指定子sql

<resultMap type="person" id="selectPersonByIdLazyRM" extends="BaseResultMap">
	<collection property="orderList" column="person_id" select="com.rl.sql.mapper.OrdersMapper.selectOrdersByPersonId">
	</collection>
</resultMap>
说明:

column:主sql语句查询出来的结果集的某一列作为子sql的参数
select:指定的子sql

2.映射文件中:sql

主sql:在PersonMapper.xml中

<select id="selectPersonByIdLazy" parameterType="int" resultMap="selectPersonByIdLazyRM">
		select * from person p where p.person_id = #{personId} 
</select>
    子sql:在OrdersMapper.xml中
 <!-- 延迟加载的子sql -->
  <select id="selectOrdersByPersonId" parameterType="int" resultMap="BaseResultMap">
  	select * from orders o where o.person_id = #{personId}
  </select>


3.java代码中的现象:

//执行该查询时,只发出主sql进行查询
Person1 p = session.selectOne("com.sql.mapper.PersonMapper.selectPersonByIdLazy", 4);
//用到一对多中,多的信息时,再发出子sql进行查询
System.out.println(p.getOrderList());

总结:

延迟加载优点:实现主子sql分离,拆解大sql。

3.多对一延迟加载:

1.映射文件OrdersMapper.xml中:新增resultMap,并指定子sql

<resultMap type="com.model.Orders" id="selectOrderByIdLazyRM" extends="BaseResultMap">
  	<association property="person" column="person_id" select="com.sql.mapper.Person1Mapper.selectPerson1ByIdWithRM"></association>
</resultMap>
2.映射文件中:sql

主sql:在OrdersMapper.xml中

<select id="selectOrderByIdLazy" parameterType="int" resultMap="selectOrderByIdLazyRM">
  	select * from orders o where o.order_id = #{orderId}
  </select>
子sql:在PersonMapper.xml中

<select id="selectPersonByIdLazy" parameterType="int" resultMap="selectPersonByIdLazyRM">
		select * from person p where p.person_id = #{personId} 
</select>
3.java代码中:

Orders order = session.selectOne("com.sql.mapper.OrdersMapper.selectOrderByIdLazy", 1);
System.out.println(order.getPerson());//执行该行代码时,发出子sql,进行查询

4.多对一,一对多混合情况:

<resultMap type="com.model.Orders" id="selectOrderByIdLazyRM" extends="BaseResultMap">
  	<association property="person" column="person_id" select="com.sql.mapper.Person1Mapper.selectPerson1ByIdWithRM"></association>
  	<collection property="detailList" column="order_id" select="com.sql.mapper.OrderDetailMapper.selectDetailByOrderId"></collection>
</resultMap>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值