天天看点

mybatis延迟加载策略 懒加载例子

什么是延迟加载

延迟加载就是在需要用到数据才进行加载,不需要用到数据时就不加载数据,延迟加载也称懒加载,      

好处

先从当表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表又比关联查询多表速度要快。      

坏处

因为只有当需要用到数据时才会进行数据库查询。这样在大批量数据查询时,<br/>
  因为查询工作也要消耗时间,所以可能会造成用户等待时间,并常造成用户体验下降。      

例子

接口

List<Score> findAllLazy();      

xml

<!--
    懒加载 一对一
        1.只查询 成绩
        2.使用<association  select 调用查询学生的接口  fetchType="lazy" 设置为懒加载-->
    <select id="AllLazy" resultType="student">
          select * from  student_tb where id=#{id}
    </select>
    <resultMap id="StudentListLazyMap" type="score">
        <id property="scoreid" column="scoreid"></id>
        <result property="coursename" column="coursename"></result>
        <result property="score" column="score"></result>
        <result property="studentid" column="studentid"></result>

        <association property="student" javaType="student" column="studentid"  select="AllLazy" fetchType="lazy"></association>
    </resultMap>
    <select id="findAllLazy" resultMap="StudentListLazyMap">
          select * from  score_tb;
    </select>      

测试结果

没有开启懒加载

开启懒加载

开启全局懒加载

<settings>
      <!--
          将数据库_的字段改为驼峰式写法  tb:student_name  映射为  studentName
      -->
      <setting name="mapUnderscoreToCamelCase" value="true"/>

      <!-- 开启全局懒加载-->
      <setting name="lazyLoadingEnabled" value="true"/>
      <setting name="aggressiveLazyLoading" value="false"/>


      <!--开启二级缓存-->
      <setting name="cacheEnabled" value="true"/>

  </settings>