什么是延续加载
延迟加载的意思是说,在关联查询是,利用延迟加载加载宿主信息,需要关联信息时在按照需求对关联的信息进行加载。可以大大提高我们项目的效率。
设置延迟加载
mybatis默认是不开启延迟加载需要在mabatis-config.xml中添加如下设置,将延迟加载打开。
<!-- 全局性设置懒加载。如果设为false,则所有相关联的都会被初始化加载。 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 当设置为true的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
设置项 | 描述 | 允许值 | 默认值 |
---|---|---|---|
lazyLoadingEnabled | 全局性设置懒加载。如果设为false,则所有相关联的都会被初始化加载。 | true | false | false |
aggressiveLazyLoading | 当设置为true的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。 | true | false | true |
使用collection进行懒加载
<resultMap id="xx" type="Teacher" autoMapping="true">
<id property="tid" column="tid"></id>
<collection property="students" column="tid" select="com.qf.mapper.TeacherMapper.findStudentById" fetchType="lazy">
</collection>
</resultMap>
<select id="findById" resultMap="xx">
select * from teacher
<where>
and tid=#{tid}
</where>
</select>
<select id="findStudentById" resultMap="userorders">
select * from student s where s.tid=#{id}
</select>
<!-- 如果需求只加载teacher类的信息将不会加载student,从而提高了程序运行速度,降低了执行时间-->
延迟加载调用的四个方法
hashcode() toString() equal() clone()