在數(shù)據(jù)與對象在進行mapping操作時,只有真正使用到該對象時,才進行mapping操作,以減少數(shù)據(jù)庫的開銷,從而提升系統(tǒng)性能。
但是Lazy Load也有缺點,在按需加載時會多次連接數(shù)據(jù)庫,增加數(shù)據(jù)庫的壓力,所以是否使用,需要看實際情況。
association和collection具備延遲加載功能
Mybatis默認(rèn)沒有開啟延遲加載,需要在全局配置文件中setting配置
lazyloadingEnabled:true使用延遲加載;false禁用延遲加載(默認(rèn)false)
aggressiveLazyLoading:true啟用時,完全加載(積極加載);false(按需加載);默認(rèn)為true
- 全局配置文件代碼:
<settings>
<!--打開延遲加載開關(guān)-->
<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>