注意:这里需要把查出来的数据进行命名使用别名,这样我们封装实体类的时候才能使用,因为数据库中生成的别名是随机的
select e.id,e.name,e.age,d.id did,d.name dname from employee e
left join dept d
on e.dept_id = d.id
did,dname就是部门的id和名称
这里还需要使用resultMap,不是使用resulttype
多对一也有两种方式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace表示命名空间 保证它是唯一 cn.itsource.mybatis.dao.impl.ProductDaoImpl + id="getUserById"--> <mapper namespace="_03_manytoone.EmployeeMapper"> <!-- 多对一操作 查询员工的同时 查询部门 一条sql--> <select id="query01" resultMap="employeeMp"> select e.id,e.name,e.age,d.id did,d.name dname from employee e left join dept d on e.dept_id = d.id </select> <!--id 结果Map的值 type:返回类型 (嵌套结果一条sql)--> <resultMap id="employeeMp" type="_03_manytoone.Employee"> <id property="id" column="id"></id> <result property="name" column="name"></result> <result property="age" column="age"></result> <association property="dept" javaType="_03_manytoone.Dept"> <id property="id" column="did"></id> <result property="name" column="dname"></result> </association> </resultMap> <!-- 多对一操作 嵌套查询(在查询出来的值dept_id,在根据dept_id这个值去查询另外东西) 1+N条sql --> <select id="query02" resultMap="employeeMp1" > select * from employee e </select> <resultMap id="employeeMp1" type="_03_manytoone.Employee"> <id property="id" column="id"></id> <result property="name" column="name"></result> <result property="age" column="age"></result> <association property="dept" column="dept_id" select="getDeptById"> </association> </resultMap> <select id="getDeptById" parameterType="long" resultType="_03_manytoone.Dept" > select * from dept where id=#{id} </select> </mapper>