一、立即加载和延迟加载
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>
未使用延迟加载之前
使用延迟加载之后
四、小总结
使用延迟加载的前提是多表查询,只有在多表查询的时候,我们才可能使用延迟加载。在使用延迟加载的时候,需要在主配置文件中进行配置延迟加载的策略,注意配置的位置。