延迟加载
如果查询订单并且关联查询用户(一对一),如果先查询订单信息即可满足需求,当我们需要查询用户信息时,再查询用户信息,把对用户信息的按需求去查询就是延迟加载。resultmap可以实现高级映射,association、collection
标签具备延迟加载功能,可以实现一对一及一对多映射。
第一步:在sqlMapConfig.xml中开启延迟加载。
<settings>
<!--打开延迟加载的开关,lazyLoadingEnabled默认是false-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--把积极加载换成消极加载,默认是true-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
第二步:定义Mapper.xml。
<resultMap type="orders" id="findOrderUserLazyLoadingResultMap">
<id column="id" property="id"/>
<result column="user_id" property="user_id"/>
<result column="number" property="number"/>
<result column="createTime" property="createTime"/>
<result column="note" property="note"/>
<result column="updateTime" property="updateTime"/>
<!--当我们调用getUser()这个方法时,<association>标签的内容才会执行。
select:执行延迟加载的statement的id。
column:订单信息中,关联查询用户的列,就是user_id。
要使用UserMapper.xml中的selectUserById这个Statement,注意要加上namespace属性。
<collection>的延迟加载和<association>类似。
-->
<association property="user" javaType="user" select= selectUserById" column="user_id">
</association>
</resultMap>
<select id="findOrderUserLazyLoading" resultMap="findOrderUserLazyLoadingResultMap">
select * from orders
</select>
第三步:定义Mapper.java
public List<Orders> findOrderUserLazyLoading() throws Exception;
第四步:测试
执行上面方法findOrderUserLazyLoading,只查询Orders信息。
在程序中遍历上一步查出来的List
延迟加载,去调用UserMapper.xml中的findUserById这个方法获取用户信息。