Mybatis查询结果部分字段为null,返回类型resultMap与resultType区别

场景描述:

       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自定义设置字段对应。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值