延迟加载

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

主要是通过 association、collection 实现一对一及一对多映射。association、collection 具备延迟加载功能。

注:这里只演示了一对多的延时加载,立即加载请自己思考
实现步骤:

setting

官方文档说明
SqlMapConfig.xml加上
两个配置文件:

IAcountDao.XML
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.qut.dao.IAccount">
    <select id="findAll" resultType="account">
        select * from account
    </select>
    <select id="findByUid" resultType="account" parameterType="int">
        select  * from account where uid=#{uid}
    </select>
</mapper>
<resultMap id="userMap" type="cn.qut.enities.User">
<!--    <id column="id" property="id"></id>-->
<!--    <result column="username" property="username"/>-->
<!--    <result column="address" property="address"/>-->
<!--    <result column="sex" property="sex"/>-->
<!--    <result column="birthday" property="birthday"/>-->
    <!-- collection 是用于建立一对多中集合属性的对应关系
    ofType 用于指定集合元素的数据类型
    select 是用于指定查询账户的唯一标识(账户的 dao 全限定类名加上方法名称)
    column 是用于指定使用哪个字段的值作为条件查询
    -->
    <collection property="accounts" ofType="account" select="cn.qut.dao.IAccount.findByUid" column="id"></collection>

</resultMap>



    <!-- 配置查询所有操作 -->
    <select id="findAll" resultMap="userMap" >
        select * from user
    </select>

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

</mapper>

测试类

  @Test
    public void findAllTest(){
        List<User> userList = userDao.findAll();
        for (User user:userList
             ) {
            System.out.println(user.toString());
//            System.out.println(user.getAccounts());
        }
    }

只执行findAll时:在这里插入图片描述
当不调用getAccounts时:
不调用getAccount时
可见mybatis还是准备了prestatement语句,但是没有执行
当调用getAccounts时:
调用时
可见执行了Preparing语句

综上,实现了延迟加载的要求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值