延迟加载
- 就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载.
- 优点:先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。
- 缺点:因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗时间,所以可能造成用户等待时间变长,造成用户体验下降。
实现延迟加载
- association、collection 具备延迟加载功能。
使用 assocation 实现延迟加载
- 账户的持久层 DAO 接口
- 账户的持久层 映射文件
- select : 填写我们要调用的 select 映射的 id
- column : 填写我们要传递给 select 映射的参数
<resultMap id="AccountU" type="com.lwb.domain.Account">
<!--建立对应关系-->
<id property="id" column="aid"></id>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
<!--它是用于指定从表方的引用实体属性的-->
<association property="user" javaType="com.lwb.domain.User" select="com.lwb.dao.IUserDao.findById" column="uid">
</association>
</resultMap>
- 用户的持久层 接口和 映射文件
- 开启 Mybatis 的延迟加载策略
SqlMapConifg.xml
- 测试
- 使用懒加载,没有用到数据的时候
@Test
public void test11()throws Exception {
// 第五步:执行dao中的方法
List<Account> accounts = accountDao.findAll();
}
- 使用到数据的时候
@Test
public void test11()throws Exception {
// 第五步:执行dao中的方法
List<Account> accounts = accountDao.findAll();
for (Account account:accounts) {
System.out.println(account.getUser());
}
}
使用 Collection 实现延迟加载
- 同样我们也可以在一对多关系配置的
<collection>
结点中配置延迟加载策略。
<collection>
结点中也有 select 属性,column 属性。
- 在 在 User 实体类中加入
List<Account>
属性
- 编写用户和账户持久层接口的方法
- IUserDao接口
List<User> findAll();
- IAccountDao接口
/**
* 根据用户 id 查询账户信息
* @param uid
* @return
*/
List<Account> findByUid(Integer uid);
- 编写用户持久层映射 配置
- collection 是用于建立一对多中集合属性的对应关系
- ofType 用于指定集合元素的数据类型
- select 是用于指定查询账户的唯一标识(账户的 dao 全限定类名加上方法名称)
- column 是用于指定使用哪个字段的值作为条件查询
<resultMap id="UserA" type="com.lwb.domain.User">
<id property="id" column="id"></id>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<result column="address" property="address"/>
<collection property="accounts" ofType="com.lwb.domain.Account" select="com.lwb.dao.IAccountDao.findByUid" column="id">
</collection>
</resultMap>
<select id="findAll" resultMap="UserA">
select * from USER
</select>
- 编写账户持久层映射配置
- 测试
- 延迟加载
@Test
public void test12()throws Exception {
// 第五步:执行dao中的方法
List<User> users = dao.findAll();
}
- 非延迟加载
@Test
public void test12()throws Exception {
// 第五步:执行dao中的方法
List<User> users = dao.findAll();
for (User user:users){
System.out.println(user+" "+user.getAccounts());
}
}