1.首先在核心配置文件:sqlMapConfig.xml 中开启延迟加载
开启延迟加载的配置, settings放在最上面
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
说明:
lazyLoadingEnabled:延迟加载总开关
aggressiveLazyLoading:
cacheEnabled:二级缓存开关
2.一对多延迟加载:
1.映射文件PersonMapper.xml中新增:resultMap并指定子sql
<resultMap type="person" id="selectPersonByIdLazyRM" extends="BaseResultMap">
<collection property="orderList" column="person_id" select="com.rl.sql.mapper.OrdersMapper.selectOrdersByPersonId">
</collection>
</resultMap>
说明:
column:主sql语句查询出来的结果集的某一列作为子sql的参数
select:指定的子sql
2.映射文件中:sql
主sql:在PersonMapper.xml中
<select id="selectPersonByIdLazy" parameterType="int" resultMap="selectPersonByIdLazyRM">
select * from person p where p.person_id = #{personId}
</select>
子sql:在OrdersMapper.xml中
<!-- 延迟加载的子sql -->
<select id="selectOrdersByPersonId" parameterType="int" resultMap="BaseResultMap">
select * from orders o where o.person_id = #{personId}
</select>
3.java代码中的现象:
//执行该查询时,只发出主sql进行查询
Person1 p = session.selectOne("com.sql.mapper.PersonMapper.selectPersonByIdLazy", 4);
//用到一对多中,多的信息时,再发出子sql进行查询
System.out.println(p.getOrderList());
总结:
延迟加载优点:实现主子sql分离,拆解大sql。
3.多对一延迟加载:
1.映射文件OrdersMapper.xml中:新增resultMap,并指定子sql
<resultMap type="com.model.Orders" id="selectOrderByIdLazyRM" extends="BaseResultMap">
<association property="person" column="person_id" select="com.sql.mapper.Person1Mapper.selectPerson1ByIdWithRM"></association>
</resultMap>
2.映射文件中:sql
主sql:在OrdersMapper.xml中
<select id="selectOrderByIdLazy" parameterType="int" resultMap="selectOrderByIdLazyRM">
select * from orders o where o.order_id = #{orderId}
</select>
子sql:在PersonMapper.xml中
<select id="selectPersonByIdLazy" parameterType="int" resultMap="selectPersonByIdLazyRM">
select * from person p where p.person_id = #{personId}
</select>
3.java代码中:
Orders order = session.selectOne("com.sql.mapper.OrdersMapper.selectOrderByIdLazy", 1);
System.out.println(order.getPerson());//执行该行代码时,发出子sql,进行查询
4.多对一,一对多混合情况:
<resultMap type="com.model.Orders" id="selectOrderByIdLazyRM" extends="BaseResultMap">
<association property="person" column="person_id" select="com.sql.mapper.Person1Mapper.selectPerson1ByIdWithRM"></association>
<collection property="detailList" column="order_id" select="com.sql.mapper.OrderDetailMapper.selectDetailByOrderId"></collection>
</resultMap>