Employee selectOneEmployee(int id);
我们以查询单个员工为例 , resultMap 与sql 如下
<!--定义resultMap-->
<resultMap id="employeeMap1" type="Employee">
<id column="id" property="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<!--fetchType为查询的类型,这里选择lazy select为嵌套查询-->
<association property="dept" javaType="Dept" fetchType="lazy"
select="selectDept" column="deptId">
<result column="name" property="name"/>
</association>
</resultMap>
<select id="selectOneEmployee" resultMap="employeeMap1">
select id,name,age,deptId from employee where id=#{id}
</select>
<!--通过上一级sql提供的deptId查询-->
<select id="selectDept" resultType="Dept">
select name from dept where id=#{deptId}
</select>
此处一对一 ,我们使用<association>
java测试 :?
public static void main(String[] args) {
SqlSession sqlSession= MybatisUtil.getSqlSession();
EmployeeDao mapper=sqlSession.getMapper(EmployeeDao.class);
Employee employee = mapper.selectOneEmployee(3);
System.out.println(employee);
System.out.println(employee.getDept());
sqlSession.commit(); //提交事务
sqlSession.close(); //关闭
查询结果 :
通过结果可以看到 , 当我们第一次输出这个 employee 对象时, 部门是没有被查询的 , 而当我们需要使用到部门的信息时, 才会去触发这个查询?
查询部门 resultMap 与 sql如下:?
<resultMap id="deptMap1" type="Dept">
<id column="id" property="id"/>
<result column="name" property="name"/>
<!--collection为一对多 , 这里一个部门包含多个员工-->
<collection property="list" javaType="List" ofType="Employee"
select="selectEmployee" fetchType="lazy" column="id">
<result property="name" column="name"/>
</collection>
</resultMap>
<select id="selectOneDept" resultMap="deptMap1">
SELECT id,name FROM dept where id=#{id}
</select>
<select id="selectEmployee" resultType="Employee">
select name from employee where deptId=#{id}
</select>
一对多,我们使用<collection>
懒加载就介绍到这里,感谢阅读