Mybatis是否支持延迟加载?如果支持,它的实现原理是什么?
Mybatis仅支持association关联对象和collection关联集合对象的延迟加载,association指的就是一对一,多对一,collection指的就是一对多,多对多查询。在Mybatis配置文件中,可以配置是否启用延迟加载lazyLoadingEnabled=true|false
延迟加载代码实现(一对多collection 查询部门时,查出该部门的员工):
实体:Dept Emp
需要在Dept中加入private List<Emp> empList; 和getter setter (即构造方法)
dao: DeptDao: /** * 查询所有部门 * @return */ List<Dept> listAll(); EmpDao: /** * 根据部门编号获取员工 * @param deptNo * @return */ List<Emp> listEmpByDeptNo(int deptNo);
配置文件:
DeptMapper.xml :
<!--查询所有部门--> <select id="listAll" resultMap="deptEmp"> select * from dept </select> <!--映射--> <resultMap id="deptEmp" type="com.aaa.mybatis.entity.Dept"> <id property="deptNo" column="deptno"/> <result property="deptName" column="deptname"/> <result property="loc" column="loc"/> <collection property="empList" column="deptno" ofType="com.aaa.mybatis.entity.Emp" select="com.aaa.mybatis.dao.EmpDao.listEmpByDeptNo"> </collection> </resultMap>
EmpMapper.xml:
<!--根据部门编号获取员工--> <select id="listEmpByDeptNo" resultType="com.aaa.mybatis.entity.Emp"> select empno,empname,salary from emp where deptno=#{deptNo} </select>
主配置文件:mybatis-config.xml 中的 settings
<!--开启全局懒加载--> <setting name="lazyLoadingEnabled" value="true"></setting>
测试:
/** * 测试延时加载 */ @Test public void testListAll(){ SqlSession sqlSession = null; try { sqlSession = SqlSessionFacotryUtil.getSqlSession(); DeptDao deptDao = sqlSession.getMapper(DeptDao.class); List<Dept> depts = deptDao.listAll(); if(depts!=null&&depts.size()>0){ for (Dept dept : depts) { dept.getEmpList(); } } } catch (Exception e) { e.printStackTrace(); } finally { if(sqlSession!=null) sqlSession.close(); } }
如果下面代码注释掉,开启懒加载,底层查询数据库时,只执行了部门查询,如果不开启懒加载,部门和该部门的员工都查询了 if(depts!=null&&depts.size()>0){ for (Dept dept : depts) { dept.getEmpList(); } }
association指的就是一对一,多对一:
/*实体加入*/
private Ictionaries ictionaries; <!-- 通用查询映射结果 --> <resultMap id="CustomerIctionaries" type="com.aaa.entity.Customer"> <id column="customer_id" property="customerId" /> <result column="name" property="name" /> <result column="sex" property="sex" /> <result column="type_id" property="typeId" /> <result column="purchase_quantity" property="purchaseQuantity" /> <result column="purchase_purpose" property="purchasePurpose" /> <result column="purchase_date" property="purchaseDate" /> <result column="nationality" property="nationality" /> <result column="certificateType" property="certificateType" /> <result column="identification_number" property="identificationNumber" /> <result column="date_birth" property="dateBirth" /> <result column="home_address" property="homeAddress" /> <result column="residential_address" property="residentialAddress" /> <result column="issuing_authority" property="issuingAuthority" /> <result column="work_unit" property="workUnit" /> <result column="remarks" property="remarks"/> <association property="ictionaries" javaType="com.aaa.entity.Ictionaries"> <result property="code" column="code"/> </association> </resultMap>