版权声明:[ws - 兮的博客] - 空间专属,未经声明不得私自转载 https://blog.csdn.net/qq_41463655/article/details/82321017
延迟加载:使用到数据才发出sql查询
sqlMapConfig.xml 配置文件中
<settings>
<!-- 延迟加载的总开关-->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- aggressiveLazyLoading 设置成false才是启用延迟加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启二级缓存,在mybatis中只要缓存的配置都指的是二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
对应的映射文件中
<!-- ======================== 一对多的延迟加载 =========================== -->
<resultMap type="person" id="selectPersonByIdLazyRM" extends="BaseResultMap">
<!-- column:把 外键id传送子sql 主sql查询出来的结果中的某一列作为子sql的参数
select:子sql的位置 -->
<collection property="orderList" column="person_id" select="com.rl.mapper.OrdersMapper.selectOrdersByPersonIdLazy"></collection>
</resultMap>
主sql 主映射文件中,
<select id="selectPersonByIdLazy" parameterType="int" resultMap="selectPersonByIdLazyRM">
select * from person t where t.person_id = #{personId}
</select>
子sql(可以在另外一个映射文件中)
要通过主sql返回的值来查询的映射文件中<select id="selectOrdersByPersonIdLazy" parameterType="int" resultMap="selectPersonByIdLazyRM">
select * from person t where t.person_id = #{personId}
</select>
<!-- ======================== 多对一的延迟加载 =========================== -->
和一对多大同小异,把 collection 换成 association
子sql中指定的字段的映射关系,所以不在需要指定字段映射
可以同时指定一对多,多对一的延迟加载
使用方法
一对一 == 多对一
多对一 == 多对一
一对多 == 一对多
多对多 == 一对多(从两端看)