Mybatis(15)Mybatis延迟加载/缓存

 复制项目day03_eesy_03one2many到新建的项目day04_eesy_01lazy

1.删除项目中AccountUser类

2.IAccountDao接口中只保留findAll()

3.AccountTest类只保留testFindAll()

实现一对一延迟加载

4.更改IAccountDao.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="com.itheima.dao.IAccountDao">
    <!--定义封装account和user的resultMap-->
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!--一对一关系映射,配置封装user的内容-->
       
    </resultMap>
    <!--查询所有-->
    <select id="findAll" resultMap="accountUserMap">
        select * from account
    </select>
    
</mapper>

5.测试AccountTest中的findAll方法

配置延迟加载

更改IAccountDao.xml

<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>
    

此时执行testFindAll(),结果如下

 

 并未实现一对一延迟加载

百度mybatis在xml中找到setting,更改SqlMapConfig.xml配置文件

<configuration><configuration>中加入下列配置
<!--配置参数-->
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"></setting>
    </settings>

测试结果

 

一对多情况下的延迟加载

1.IUserDao和IUserDao.xml

//根据id查询用户信息
    User findById(Integer userId);



//IUserDao.xml
<!--根据id查询用户-->
    <select id="findById" parameterType="INT" resultType="user">
        select * from user where id=#{userId};
    </select>
<!--配置user对象中accounts集合的映射,property是配置集合的名字ofType是集合元素类型accounts-->
        <collection property="accounts" ofType="account" select="com.itheima.dao.IAccountDao.findAccountByUid" column="id">
        </collection>

2. IAccountDao和IAccountDao.xml

 //根据用户id查询账户信息
    List<Account> findAccountByUid(Integer uid);

//IAccountDao.xml
<!--查询一条账户信息-->
    <select id="findAccountByUid" resultType="account">
        select * from account where id=#{uid}
    </select>

3.测试,实现了一对多的延迟加载

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值