mybatis的加载(延时加载和懒加载)

1 延迟加载

<!--        设置字段名来作为javabean的属性-->
        <setting name="useColumnLabel" value="true"/>
<!--        开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"></setting>

<mapper namespace="org.zhang.mapper.EmpMapper">
    <resultMap id="EmpDeptReslt" type="Emp">
        <id column="empno" property="no"></id>
        <result column="ename" property="name"></result>
        <result column="job" property="job"></result>
        <result column="hiredate" property="hiredate"></result>
        <result column="sal" property="sal"></result>
        <!--  property  emp类中的关联属性    select 关联执行的sql     javaType 结果集类型   column 两张表的关联字段 (外键) fetchType (lazy(懒加载)   eager(不是懒加载) )  -->
       
         <association property="dept" select="org.zhang.mapper.DeptMapper.selectDeptById" javaType="Dept" column="deptno">

        </association>
    </resultMap>
    <select id="selecgtEmpById"  parameterType="int" resultMap="EmpDeptReslt">
            select * from emp where empno = #{empno}
    </select>
</mapper> 
<mapper namespace="org.zhang.mapper.DeptMapper">
    <select id="selectDeptById"  parameterType="int"  resultType="Dept">
        select * from dept where deptno = #{deptNo}
    </select>
</mapper>

2 一对多的关联查询的懒加载

<mapper namespace="org.zhang.mapper.DeptMapper">
    <resultMap id="deptAndEmps" type="Dept">
        <id column="deptno" property="deptno"></id>
        <result column="dname" property="dname"></result>
        <result column="loc" property="loc"></result>
        <collection property="emps"  ofType="Emp" select="org.zhang.mapper.EmpMapper.selectEmpByDeptNo" column="deptno" >

        </collection>
    </resultMap>
    <select id="selectDeptById"  parameterType="int"  resultMap="deptAndEmps">
        select * from dept where deptno = #{deptNo}
    </select>
</mapper>
<mapper namespace="org.zhang.mapper.EmpMapper">
    <resultMap id="EmpReslt" type="Emp">
        <id column="empno" property="no"></id>
        <result column="ename" property="name"></result>
        <result column="job" property="job"></result>
        <result column="hiredate" property="hiredate"></result>
        <result column="sal" property="sal"></result>
    </resultMap>
    <select id="selecgtEmpById"  parameterType="int" resultMap="EmpReslt" >
            select * from emp where empno = #{empno}
    </select>
    <select id="selectEmpByDeptNo" parameterType="int" resultMap="EmpReslt">
        select * from emp where deptno=#{deptno}
    </select>
</mapper>

你可能感兴趣的:(mybatis的加载(延时加载和懒加载))