六、延迟加载

在数据与对象在进行mapping操作时,只有真正使用到该对象时,才进行mapping操作,以减少数据库的开销,从而提升系统性能。

但是Lazy Load也有缺点,在按需加载时会多次连接数据库,增加数据库的压力,所以是否使用,需要看实际情况。
association和collection具备延迟加载功能

Mybatis默认没有开启延迟加载,需要在全局配置文件中setting配置
lazyloadingEnabled:true使用延迟加载;false禁用延迟加载(默认false)
aggressiveLazyLoading:true启用时,完全加载(积极加载);false(按需加载);默认为true

  • 全局配置文件代码:
<settings>
  <!--打开延迟加载开关-->
  <setting name="lazyloadingEnabled" value="true"/>
  <!--改为按需加载-->
  <setting name="aggressiveLazyLoading" value="false"/>
</settings>
  • EmpMapper.java代码:
    public List<Emp> getEmpLazy();
    public List<Dept> getDeppLazy();
  • EmpMapper.xml代码:
 <select id="getEmpLazy" resultMap="_empdeptlazy">
    select * from emp
 </select>
 <resultMap type="Emp" id="_empdeptlazy" autoMapping="true">
    <association property="dept" javaType="Dept" select="getDeptByDeptno" column="deptno"></association>
 </resultMap>
 <select id="getDeptByDeptno" parameterType="int" resultType="Dept">
    select * from dept where deptno =#{deptno}
 </select>
 
 <select id="getDeppLazy" resultMap="_deptemplazy">
    select * from dept
 </select>
 <resultMap type="Dept" id="_deptemplazy" autoMapping="true">
    <id column="deptno" property="deptno"/>
    <collection property="emps" ofType="Emp" select="getEmpByDeptno" column="deptno"></collection>
 </resultMap> 
 <select id="getEmpByDeptno" parameterType="int" resultType="Emp">
    select * from emp where deptno =#{deptno}
 </select>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容