使用mybatis的延迟加载,需要两个步骤:
1.在全局配置文件中添加一下语句(lazyLoadingEnabled默认为false,aggressiveLazyLoading默认为true)
<settings> <!-- 延迟加载总开关 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 侵入式延迟 --> <setting name="aggressiveLazyLoading" value="false"/> </settings>
2.写好映射文件
<resultMap type="User" id="CacheTest"> <id column="id" property="id" /> <result column="username" property="username" /> <result column="birthday" property="birthday" /> <result column="address" property="address" /> <!-- column相当于传入parameter ofType相当于resultType --> <collection property="orderList" column="id" ofType="Order" select="resultMap.resultMapMapper.CacheTestSelect"> <result column="number" property="number" /> <result column="createtime" property="createtime" /> </collection> </resultMap> <select id="CacheTest" resultMap="CacheTest"> select * from user </select> <select id="CacheTestSelect" parameterType="int" resultType="Order"> select * from orders where user_id = #{id} </select>
这样查询一开始会执行select * from user
然后当读取到orderList时才会执行select * from orders where user_id = #{id}