mybatis踩坑小记
在写查询SQL时,务必要带一个非空字段作为结果集,否则当查询结果字段均为空值时,返回的集合size为1,但是对象为null,从而引发空指针。
具体看下述例子:
--dao层代码
List<TempPo> getTempInfo(String tempId);
--mapper文件
<select id="getTempInfo" resultMap="com.demo.TempPo" parameterType="String">
select a,b from temp where tempId = #{tempId};
</select>
若a,b字段均为空的情况,此时返回的集合非空,且size为 1,通过下述集合非空校验,但是在取对象的字段时爆空指针
--程序逻辑
if(tList != null && tList.size()>1){
tList.get(0).getA(); //出现空指针
}
需调整为:
<select id="getTempInfo" resultMap="com.demo.TempPo" parameterType="String">
select a,b,tempId from temp where tempId = #{tempId};
</select>