MyBatis——第3章 关联关系查询(二)

3.2 延迟加载

       MyBatis 中的延迟加载,也成为懒加载,是指在进行关联查询时,按照设置规则推迟对关联对象的select查询,延迟加载能有效地减小数据库的压力。

仅仅对关联对象的select查询进行延迟,对于主加载对象都是直接执行查询语句的。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.dao.INewsLabelDao">

关联查询-延迟加载
<select id="selectNewslabelByParent" resultMap="newsLabelMapper">
	select id,name from newslabel where pid = #{id}
</select>


<resultMap type="Newslabel" id="newsLabelMapper">
	<id column="id" property="id"/>
	<result column="name" property="name"/>
	<collection property="children" 
				ofType="NewsLabel"
				select="selectNewslabelByParent"
				column="id"/>
</resultMap>

主查询- 直接加载 
<select id="selectNewsLabelById" resultMap="newslabelMapper">
	select id,name from newslabel where id=#{id}
</select>
	
</mapper>

3.2.1 关联对象加载时机

直接加载:多表连接查询就是直接加载,无法延迟加载。

侵入式延迟:对主加载对象详情的查询会直接引起对关联加载的查询。

深度延迟:需要访问关联对象的时候再去查。

设置如下:

	<!--设置整个应用所使用的常量值 -->
	<settings>
		<!--延迟加载的总开关 -->
		<setting name="LazyLoadingEnable" value="true"/>
		<!--侵入式延迟加载开关  -->
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>
	@Test
	public void test01(){
		Country country = dao.selectCountryById(2);
		System.out.println(country.getCname());
		Set<Minister> ministers = country.getMinisters();
		System.out.println(ministers.size());
	}

今日内容总结:

Mapper动态代理:

     ①:保证sql id和接口名方法名重名

     ②:namespace名 改成接口的全名 

     ③:调用dao = sqlSession.getMapper(...接口dao.class)

动态SQL:

    解决查询条件不固定,可以动态组合

关联查询:

   

猜你喜欢

转载自blog.csdn.net/Curry7895/article/details/82806139
今日推荐