延迟加载:
就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载。
好处:先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。
坏处:
因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗时间,所以可能造成用户等待时间变长,造成用户体验下降。
主要是通过 association、collection 实现一对一及一对多映射。association、collection 具备延迟加载功能。
注:这里只演示了一对多的延时加载,立即加载请自己思考
实现步骤:
setting
两个配置文件:
IAcountDao.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="cn.qut.dao.IAccount">
<select id="findAll" resultType="account">
select * from account
</select>
<select id="findByUid" resultType="account" parameterType="int">
select * from account where uid=#{uid}
</select>
</mapper>
<resultMap id="userMap" type="cn.qut.enities.User">
<!-- <id column="id" property="id"></id>-->
<!-- <result column="username" property="username"/>-->
<!-- <result column="address" property="address"/>-->
<!-- <result column="sex" property="sex"/>-->
<!-- <result column="birthday" property="birthday"/>-->
<!-- collection 是用于建立一对多中集合属性的对应关系
ofType 用于指定集合元素的数据类型
select 是用于指定查询账户的唯一标识(账户的 dao 全限定类名加上方法名称)
column 是用于指定使用哪个字段的值作为条件查询
-->
<collection property="accounts" ofType="account" select="cn.qut.dao.IAccount.findByUid" column="id"></collection>
</resultMap>
<!-- 配置查询所有操作 -->
<select id="findAll" resultMap="userMap" >
select * from user
</select>
<select id="findById" resultType="user" parameterType="int">
select * from user where id=#{id}
</select>
</mapper>
测试类
@Test
public void findAllTest(){
List<User> userList = userDao.findAll();
for (User user:userList
) {
System.out.println(user.toString());
// System.out.println(user.getAccounts());
}
}
只执行findAll时:
当不调用getAccounts时:
可见mybatis还是准备了prestatement语句,但是没有执行
当调用getAccounts时:
可见执行了Preparing语句
综上,实现了延迟加载的要求。