Mybatis操作数据库报空指针的解决
背景
环境:Springboot+ mybatis
今天,报了个很奇怪的空指针异常,排查了一会,最终才发现问题,记录一下。
报错信息
exception found: java.lang.NullPointerException, null
java.lang.NullPointerException: null
mybatis的dao代码
List<UserInfo> queryUserInfo(@Param("name") String name, @Param("mobile") String mobile, @Param("status")byte status);
SELECT *
from
user_info user
LEFT JOIN user_rule_map map ON user.id = map.userId
LEFT JOIN user_info truck ON rule.id = map.ruleId
<where>
<if test="name != null">
user.name=#{name,jdbcType=VARCHAR}
</if>
<if test="mobile != null">
and user.mobile=#{mobile,jdbcType=VARCHAR}
</if>
<if test="status != null">
and map.status=#{status,jdbcType=TINYINT}
</if>
</where>
</select>
错误原因
排查了半天,才发现status的类型写成了byte类型。
我们知道,Mybatis的 #{} 是调用了PreparedStatement的set方法,如果不是对象而是基本类型的话,是拿不到这个status的值的,而且这里指定了jdbcType=TINYINT。
解决
status的类型改为byte的包装类 Byte
反思
- 在Mybatis中如果单独传递参数,参数类型必须是对象类型(基本类型是其包装类)
- 如果是自定义对象,必须实现/重写其Get/Set方法