mybatis文件映射之利用association进行关联查询(二)
与初探中大部分一样,只是修改resultMap中的相关信息。
<resultMap type="com.gong.mybatis.bean.Employee" id="MySimpleMap2"> <id column="id" property="id"/> <result column="last_name" property="lastName"/> <result column="gender" property="gender"/> <result column="email" property="email"/> <association property="dept" javaType="com.gong.mybatis.bean.Department"> <id column="did" property="id"/> <result column="dept_name" property="deptName"/> </association> </resultMap> <select id="getEmpAndDept" resultMap="MySimpleMap2"> SELECT e.id,e.last_name,e.gender,e.email,d.dept_name,d.id did FROM tbl_employee e,tbl_department d WHERE e.d_id = d.id and e.id=#{id}; </select>
说明:在resultMap中使用association标签,property属性对应着Employee中的成员属性的名称,javaType对应着该成员属性的类型,子标签id标识tbl_department中的主键,因为我们在select标签中将d.id取别名did,所以将did映射给Department中的id属性,然后通过result标签将普通的字段映射给Department中的deptName属性。
结果:
DEBUG 01-20 12:42:43,808 ==> Preparing: SELECT e.id,e.last_name,e.gender,e.email,d.dept_name,d.id did FROM tbl_employee e,tbl_department d WHERE e.d_id = d.id and e.id=?; (BaseJdbcLogger.java:145)
DEBUG 01-20 12:42:43,887 ==> Parameters: 3(Integer) (BaseJdbcLogger.java:145)
DEBUG 01-20 12:42:43,926 <== Total: 1 (BaseJdbcLogger.java:145)
Employee [id=3, lastName=小红, gender=0, email=xiaohong@qq.com, dept=Department [id=1, deptName=开发部]]
Department [id=1, deptName=开发部]
说明这种方法也是可以的。