问题描述
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2
问题背景
目标:通过Collection处理一对多的映射关系——使用部门id,查询部门的相关信息,包括部门的员工列表,返回的部门信息映射到Dept实体。
疑惑:通过1个id只能查到1个部门,尽管因为有多个员工,在数据库中显示多个记录,但是也不会造成“TooManyResultsException”这样的错误。
Dept类代码
public class Dept {
private Integer deptId;
private String deptName;
private List<Emp> emps;
// 省略构造方法、get/set方法、toString方法
}
DeptMapper接口代码
public interface DeptMapper {
/**
* 查询部门以及部门中的员工信息
* @param deptId
* @return
*/
Dept getDeptAndEmpByEmpId(@Param("deptId") Integer deptId);
}
DeptMapper.xml文件代码
<mapper namespace="com.atguigu.mybatis.mapper.DeptMapper">
<resultMap id="deptAndEmpResultMap" type="Dept">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName" ></result>
<!-- ofType设置集合类型的属性中存储的数据的类型 -->
<collection property="emps" ofType="Emp">
<id column="empId" property="emp_id"></id>
<result column="empName" property="emp_name"></result>
<result column="age" property="age"></result>
<result column="gender" property="gender"></result>
</collection>
</resultMap>
<!-- Dept getDeptAndEmpByEmpId(@Param("deptId") Integer deptId); -->
<select id="getDeptAndEmpByEmpId" resultMap="deptAndEmpResultMap">
SELECT *
FROM t_dept
LEFT JOIN t_emp
ON t_dept.dept_id = t_emp.dept_id
WHERE t_dept.dept_id = #{deptId}
</select>
</mapper>
导致原因
DeptMapper.xml映射文件中的resultMap的id、result标签的property、column属性写反了。