MyBatis 延迟加载

xiaoxiao2021-02-28  12

MyBatis中的延迟加载,也称作懒加载,是指在进行关联查询时,按照设置的延迟规则推迟关联对象select查询。

延迟加载可以有效的减少数据库压力

MyBatis的延迟加载是对关联对象的查询有延迟设置,对于主加载对象都是直接执行查询语句的。

MyBatis根据对关联对象查询的select语句的执行时机,分为三类:直接加载侵入式延迟加载深度延迟加载

直接加载:即不延迟加载,执行完主加载对象的select语句,马上执行对关联对象的select查询

侵入式延迟加载侵入的意思是,关联对象查询的详情侵入主加载对象详情中执行完主加载对象的select语句,不会执行对关联对象的select查询。当访问主加载对象详情时,才会执行关联对象的select查询。

深度延迟加载执行完主加载对象的select语句,不会执行关联对象select查询。访问主加载对象详情时也不会执行关联对象的select查询。只有当真正访问关联对象详情时,才会执行关联对象select查询。

1、修改mybatis.xml主配置文件

1)直接加载

<settings> <!-- 延迟加载的总开关 false:关闭 不启动延迟加载,则为直接加载 --> <setting name="lazyLoadingEnabled" value="false"/> <settings/>

2)侵入式延迟加载

<settings> <!-- 延迟加载的总开关 true:开启 启动延迟加载 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 侵入式延迟加载 true:开启 启动侵入式延迟加载 --> <setting name="aggressiveLazyLoading" value="true"/> </settings>

3)深度延迟加载
<settings> <!-- 延迟加载的总开关 true:开启 启动延迟加载 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 侵入式延迟加载 false:关闭 关闭侵入式延迟加载,即启动深度延迟加载 --> <setting name="aggressiveLazyLoading" value="false"/> </settings>

2、mapper.xml配置文件

<!-- 方法1 这种多表关联查询是不会延迟加载的,就一个select,肯定不会延迟--> <resultMap type="Country" id="countryMapper"> <id column="cid" property="cid"/> <result column="cname" property="cname"/> <collection property="peoples" ofType="People"> <id column="pid" property="pid"/> <result column="pname" property="pname"/> </collection> </resultMap> <select id="selectById" resultMap="countryMapper"> select cid,cname,pid,pname from country,people where cid=countryId and cid = #{xxx} </select> <!-- 方法2 延迟后面加载的sql。也叫关联sql--> <select id="selectPeople" resultType="People"> select pid,pname from people where countryId=#{ooo} </select> <resultMap type="Country" id="countryMapper2"> <id column="cid" property="cid"/> <result column="cname" property="cname"/> <collection property="peoples" ofType="People" select="selectPeople" column="cid" /> </resultMap> <select id="selectById2" resultMap="countryMapper2"> select cid,cname from country where cid = #{xxx} </select>

3、延迟加载策略

转载请注明原文地址: https://www.6miu.com/read-1650356.html

最新回复(0)