六、MyBatis中的延迟加载

延迟加载又叫做懒加载,就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。

好处
先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。
坏处
因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗
时间,所以可能造成用户等待时间变长,造成用户体验下降。

-----------------------------------------------------------------------------------------------------------------------------------------

实现原理个人理解:

首先mybatis的config配置文件中要声明延迟加载为true,aggressiveLazyLoading在3.4.1版本之后已经默认为false,可省略,写出来只是便于理解!

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

一对一

通过resultMap来实现,**column=“uid”**是Account自身的uid传到com.lp.dao.UserDao.selectUserById中通过uid来查询User中对应的内容。
AccountDao.xml中需要这样的语句

    <resultMap id="userAccountMap" type="account">
        <id property="id" column="id"/>
        <result property="money" column="money"/>
        <result property="uid" column="uid"/>
		
        <association property="user" column="uid" javaType="user" select="com.lp.dao.UserDao.selectUserById"></association>
    </resultMap>

	<select id="findUserAccount"  resultMap="userAccountMap">
        select * from account;
    </select>

UserDao.xml中需要这样的语句

	<select id="selectUserById" parameterType="int" resultType="user">
        select * from user
        where
        id = #{uid};
    </select>

在测试类中执行Account的findUserAccount()方法即可看见效果,记得打开日志功能!

-----------------------------------------------------------------------------------------------------------------------------------------

多对一

UserDao.xml中需要这样的语句

    <resultMap id="userAccountMap" type="user">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="birthday" column="birthday"/>
        <result property="sex" column="sex"/>
        <result property="address" column="address"/>

        <collection property="accounts" ofType="account" select="com.lp.dao.AccountDao.findAccountByUId" column="id">
        </collection>
    </resultMap>

    <select id="findAll" resultMap="userAccountMap">
        select * from user;
    </select>

AccountDao.xml中需要这样的语句

	<select id="findAccountByUId" resultType="account">
        select * from account
        where
        uid = #{uid};
    </select>

然后测试类中执行User的finAll()方法即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值