MyBatis延迟加载策略

一、立即加载和延迟加载

1、立即加载

所谓立即加载,在多表查询的时候,无论是否使用到另一张表,都立刻加载。

2、延迟加载

所谓延迟加载,就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载。
好处:先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。

3、两者的区别

立即加载和延迟加载最主要的区别是延迟加载是一种按需加载(只有在需要的时候才进行加载的一种模式),可以提高数据库的性能,而立即加载是一种直接加载的模式,可能会降低数据库的性能。

二、一对一实现延迟加载

无论是一对一实现延迟加载还是一对多实现延迟加载,都需要在主配置文件中进行配置延迟加载策略。

<settings>
	<!--配置延迟加载-->
	<setting name="lazyLoadingEnabled" value="true"/>
	<setting name="aggressiveLazyLoading" value="false"/>
</settings>

在这里插入图片描述

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.uos.dao.IAccountDao">
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="id" />
        <result property="uid" column="uid"/>
        <result property="money" column="money"/>
        <!--select属性指定要查询的方法,column属性指定查询方法的参数-->
        <association property="user" column="uid" javaType="User" select="com.uos.dao.IUserDao.findById">
        </association>
    </resultMap>
    <!--查询所有-->
    <select id="findAll" resultMap="accountUserMap" >
        select * from account;
    </select>
</mapper>

注意:在SQL语句中,我们只是查询了account信息,并没有查询user信息。在<association></association>标签中,使用select属性指定需要查询user时所使用的方法。
IUserDao.xml

<!--根据id查询用户信息-->
<select id="findById" parameterType="Integer" resultType="user">
	select * from user where id=#{id};
</select>

未使用延迟加载之前
在这里插入图片描述
使用延迟加载之后
在这里插入图片描述

三、一对多实现延迟加载

IUserDao.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.uos.dao.IUserDao">
    <resultMap id="userAccountMap" type="user">
        <id property="id" column="id" />
        <result property="username" column="username"/>
        <result property="address" column="address"/>
        <result property="sex" column="sex"/>
        <result property="birthday" column="birthday"/>
        <collection property="account" ofType="Account" column="id" select="com.uos.dao.IAccountDao.findAccountByUid">
        </collection>
    </resultMap>
    <!--查询所有-->
    <select id="findAll" resultMap="userAccountMap" >
        select * from user;
    </select>
</mapper>

IAccountDao.xml

<select id="findAccountByUid" resultType="com.uos.domain.Account" parameterType="integer">
	select * from account where uid = #{uid}
</select>

未使用延迟加载之前
在这里插入图片描述
使用延迟加载之后
在这里插入图片描述

四、小总结

使用延迟加载的前提是多表查询,只有在多表查询的时候,我们才可能使用延迟加载。在使用延迟加载的时候,需要在主配置文件中进行配置延迟加载的策略,注意配置的位置。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值