延迟加载又叫做懒加载,就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。
好处:
先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。
坏处:
因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗
时间,所以可能造成用户等待时间变长,造成用户体验下降。
-----------------------------------------------------------------------------------------------------------------------------------------
实现原理个人理解:
首先mybatis的config配置文件中要声明延迟加载为true,aggressiveLazyLoading在3.4.1版本之后已经默认为false,可省略,写出来只是便于理解!
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
一对一
通过resultMap来实现,**column=“uid”**是Account自身的uid传到com.lp.dao.UserDao.selectUserById
中通过uid来查询User中对应的内容。
AccountDao.xml中需要这样的语句
<resultMap id="userAccountMap" type="account">
<id property="id" column="id"/>
<result property="money" column="money"/>
<result property="uid" column="uid"/>
<association property="user" column="uid" javaType="user" select="com.lp.dao.UserDao.selectUserById"></association>
</resultMap>
<select id="findUserAccount" resultMap="userAccountMap">
select * from account;
</select>
UserDao.xml中需要这样的语句
<select id="selectUserById" parameterType="int" resultType="user">
select * from user
where
id = #{uid};
</select>
在测试类中执行Account的findUserAccount()方法即可看见效果,记得打开日志功能!
-----------------------------------------------------------------------------------------------------------------------------------------
多对一
UserDao.xml中需要这样的语句
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
<collection property="accounts" ofType="account" select="com.lp.dao.AccountDao.findAccountByUId" column="id">
</collection>
</resultMap>
<select id="findAll" resultMap="userAccountMap">
select * from user;
</select>
AccountDao.xml中需要这样的语句
<select id="findAccountByUId" resultType="account">
select * from account
where
uid = #{uid};
</select>
然后测试类中执行User的finAll()方法即可