场景描述:
Mapper中ResultMap已经其他对象定义,在使用ResultType作为对象类型时,发现返回的结果中部分字段为null
实体的定义:
public class PubEmp implements Serializable {
private Integer id;
private String deptCode;
private String deptName;
......
}
Mapper中对应的SQL:
<select id="queryEmpAndDept" resultType="com.wonder.hsbp.mdm.emp.domain.PubEmpAndDept">
select
a.ID,e.CODE DEPT_CODE,a.DEPT_NAME
from pub_emp a,pub_dept e
where a.DEPT_ID = e.id(+)
</select>
SQL查询结果:
单元测试输出结果:
解决办法:
参考文章:https://blog.csdn.net/u014141841/article/details/89313410
修改SQL,修改别名为对象对应的字段名称:
<select id="queryEmpAndDept" resultType="com.wonder.hsbp.mdm.emp.domain.PubEmpAndDept">
select
a.ID,e.CODE deptCode,a.DEPT_NAME deptName
from pub_emp a,pub_dept e
where a.DEPT_ID = e.id(+)
</select>
单元测试输出结果:
原因及解释:
参考文章:https://blog.csdn.net/woshixuye/article/details/27521071
1、返回类型为resultType:MyBatis会自动的把对应的值赋给resultType所指定对象的属性。
2、返回类型为resultMap:因为自定义设置了字段对应,所以进行赋值时,MyBatis会按照你自定义的映射进行赋值。
所以,当我使用了resultType进行对象赋值时,对象deptCode与SQL查询中的DEPT_CODE无法对应,所以就会被置为null,只需要将SQL中的字段别名设置与实体对象的字段名一直即可,当然也可以使用resultMap自定义设置字段对应。