Mybatis在Spring中的使用(八)

文章概述

接上文Mybatis在Spring中的使用(七)。本文主要介绍了mybatis的延迟加载机制。

延迟加载

问题:在一对多种,当我们有一个用户,它有100个账户。
在查询用户的时候,要不要把关联的账户查出来?

在查询用户时,用户下的账户信息应该是什么时候使用,什么时候查询。
在查询账户的时候,要不要把关联的用户查出来?

从业务上来看,在查询账户时账户的所属用户信息应该是随着账户查询时一起查询出来。但在查询用户时不需要把所有的账户信息立刻查出来,这就用到了mybatis的延迟加载机制

用途

在真正使用数据时,才发起查询,不用的时候不查询,也叫按需加载(懒加载)

在使用时,将mybatis的版本设置为3.5.1

使用场景

一对多,多对多:通常情况下我们都是采用延迟加载

多对一,一对一:通常情况下我们都是采用立即加载

实例

一对一实现延迟加载

在主配置文件中开启延迟加载的选项

<settings>
        <!--开启mybatis支持延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

配置需要延迟加载的对象

<resultMap id="accountUserMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!-- 一对一的关系映射:配置封装user的内容-->
        <!--select属性指定的内容,查询用户的唯一标识-->
        <!--column属性指定的内容:用户根据id查询时,所需要的参数的值-->
        <association property="user" column="uid" javaType="user" select="com.itheima.dao.IUserDao.findById">
        </association>
    </resultMap>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="accountUserMap">
        select * from account
    </select>

多对一实现延迟加载

<resultMap id="userAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <!-- 配置user对象中accounts集合的映射 -->
        <collection property="accounts" ofType="account" select="com.itheima.dao.IAccountDao.findAccountByUid"
        column="id">
        </collection>
    </resultMap>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="userAccountMap">
        select * from user
    </select>
<select id="findAccountByUid" resultType="account" parameterType="int">
        select * from account where uid = #{uid}
    </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值