第9章——Mybatis延迟加载策略

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

一:一对一 中的延迟加载

需求:查询账户(Account)信息并且关联查询用户(User)信息

使用assocation 实现延迟加载

1、创建两个实体类 (Account中应有User属性)
2、创建两个持久层接口
3、定义两映射文件
4、配置主配置文件
5、测试

IAccountDao.xml

<mapper namespace="com.itheima.dao.IAccountDao">
  <resultMap id="accountMap" type="account">
      <id column="id" property="id"/>
      <result column="uid" property="uid"/>
      <result column="money" property="money"/>
  	  <!-- 它是用于指定从表方的引用实体属性的 -->
    <association property="user" javaType="user" column="uid" select="com.itheima.dao.IUserDao.findUserById"/>
      <!--select : 填写我们要调用的 select 映射的 id
		  column  : 填写我们要传递给 select 映射的参数-->  
  </resultMap>
      <!-- 查询所有 -->
      <select id="findAll" resultMap="accountMap">
          select * from account
      </select>
</mapper>  

IUserDao.xml

<mapper namespace="com.itheima.dao.IUserDao">
    <select id="findUserById" resultType="user" parameterType="int">
        select * from USER where id = #{id}
    </select>
</mapper>

SqlMapConfig.xml

 <settings>
        <!-- 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个属性会按需加载-->
        <setting name="aggressiveLazyLoading" value="false"/>
 </settings>

二:一对多 中的延迟加载

需求:查询用户(User)信息并且关联查询账户(Account)信息

使用 collection 实现延迟加载

1、创建两个实体类 (User中应有List<Account>属性)
2、创建两个持久层接口
3、定义两映射文件
4、配置主配置文件
5、测试

IAccountDao.xml

<mapper namespace="com.itheima.dao.IAccountDao">
     <select id="findAccountById" resultType="account" parameterType="int">
        select * from account where uid = #{uid}
    </select>
</mapper>  

IUserDao.xml

<mapper namespace="com.itheima.dao.IUserDao">
 <resultMap id="userMap" type="user">
    <id property="id" column="id"></id>
    <result property="username" column="username"></result>
    <result property="birthday" column="birthday"></result>
    <result property="sex" column="sex"></result>
    <result property="address" column="address"></result>
    
    <collection property="accounts" ofType="account" column="id" select="com.itheima.dao.IAccountDao.findAccountById" />
<!-- collection 是用于建立一对多中集合属性的对应关系
ofType 用于指定集合元素的数据类型
select 是用于指定查询账户的唯一标识(账户的 dao 全限定类名加上方法名称)
column 是用于指定使用哪个字段的值作为条件查询
-->
</resultMap>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="userMap">
      select * from user
    </select>
</mapper>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值