---
title: "iBATIS也支持延迟加载"
author: "weishuwei"
date: "2009-05-12T15:56:57Z"
tags: []
slug: "ibatis"
draft: false
lastmod: "2009-05-12T15:56:57Z"
id: 384307
url: "https://weishuwei.iteye.com/blog/384307"
---

配置完ibatis的关系后,做单元测试发现关联的对象并没有被查询出来,review了一遍,没发现有什么问题,查了一下,发现是延迟加载的问题

.

iBATIS支持延迟加载，可以在sqlMapConfig.xml中配置lazyLoadingEnabled来设置，默认情况下为true，即默认开启延迟加载。  
使用延迟加载时要求符合一定的规范，如果直接使用连接语句查询出所有对象的话就不能延迟加载了。

例如：一个用户有多个地址，对应表User和Address。

&lt;resultMap id="ResultUserMap" class="User"&gt;  
    &lt;result property="userId" column="userId" /&gt;  
    &lt;result property="addressList" select="getAddressList" column="userId" /&gt;  
&lt;/resultMap&gt;  
&lt;resultMap id="ResultAddressMap" class="Address"&gt;  
&lt;/resultMap&gt;

&lt;select id="getUserList" resultMap="ResultUserMap" &gt;  
    select userId from DemoUser  
&lt;/select&gt;  
&lt;select id="getAddressList" resultMap="ResultAddressMap"&gt;  
    select userId,address from DemoAddress  
    where userId = #value#  
&lt;/select&gt;

当访问getUserList时，查询出所有用户，直到使用Address时才会去自动执行getAddressList，获取Address信息。