resultMap级联属性赋值解决多对一映射问题
实体类中除了有有参构造器外,还要再加一个无参构造器,要不然就会一直报错。
实体类
① Emp.java(get,set,toString还有构造器略)
//员工表
public class Emp {
private Integer eid;
private String empName;
private Integer age;
private String sex;
private String email;
private Dept dept;
② Dept.java(get,set,toString还有构造器略)
//部门表
public class Dept {
private Integer did;
private String deptName;
mapper接口和mapper.xml
/**
* 查询员工以及员工所对应的部门信息
*/
Emp getEmpAndDept(@Param("eid") Integer eid);
<resultMap id="empAndDeptResultMapOne" type="com.jxxy.mybatis.pojo.Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
<result property="dept.did" column="did"></result>
<result property="dept.deptName" column="dept_name"></result>
</resultMap>
<!-- Emp getEmpAndDept(@Param("eid") Integer eid); -->
<select id="getEmpAndDept" resultMap="empAndDeptResultMapOne">
select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.eid = #{eid}
</select>
数据库数据
测试
sql在数据库中查询,可以看到没得问题
用代码测试:
@Test
public void testGetEmpAndDept(){
SqlSession sqlSession= SqlSessionUtils.getSqlSession();
EmpMapper mapper=sqlSession.getMapper(EmpMapper.class);
Emp emp=mapper.getEmpAndDept(2);
emp.getDept().getDeptName();
System.out.println(emp);
}
居然报错了!!!!
### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: Cannot set value of property 'dept.did' because 'dept.did' is null and cannot be instantiated on instance of com.jxxy.mybatis.pojo.Dept. Cause:org.apache.ibatis.reflection.ReflectionException: Error instantiating class com.jxxy.mybatis.pojo.Dept with invalid types () or values (). Cause: java.lang.NoSuchMethodException: com.jxxy.mybatis.pojo.Dept.<init>()
### The error may exist in com/jxxy/mybatis/mapper/EmpMapper.xml
### The error may involve com.jxxy.mybatis.mapper.EmpMapper.getEmpAndDept
### The error occurred while handling results
### SQL: select * from t_emp left join t_dept on t_emp.did = t_dept.did where t_emp.eid = ?
### Cause: org.apache.ibatis.reflection.ReflectionException: Cannot set value of property 'dept.did' because 'dept.did' is null and cannot be instantiated on instance of com.jxxy.mybatis.pojo.Dept. Cause:org.apache.ibatis.reflection.ReflectionException: Error instantiating class com.jxxy.mybatis.pojo.Dept with invalid types () or values (). Cause: java.lang.NoSuchMethodException: com.jxxy.mybatis.pojo.Dept.<init>()
后边的省略... ...
查资料发现,要在实体类中加无参构造器,说干就干,加无参构造器后,测试通过辣!!!
Emp{eid=2, empName='李四', age=33, sex='女', email='12@12.com', dept=Dept{did=2, deptName='B', empList=null}}