不得不说代码中的null值,总是会在不经意间引起bug,也许看似低级,但是产生的问题还不小。记一下自己的踩坑过程,以此为鉴。
原始代码如下:
Long userId = UserUtil.getLoginUserId(request);
UserInterestUser userInterestUser = userService.queryOne(MapUtil.buildMap("userId", userId, "anotherUserId", 2L));
业务逻辑是根据用户的id和另一个用户的id查询该记录,mapper中的配置文件如下:
<sql id="Where_Sql">
<if test="id != null"> AND id = #{id} </if>
<if test="userId != null"> AND user_id = #{userId} </if>
<if test="anotherUserId != null"> AND another_user_id = #{anotherUserId} </if>
</sql>
所以当userId为null的时候,逻辑就变成了,仅根据anotherUserId的值查询记录。
根据问题原因对于userId为null赋值一个不存在的值,因为userId为非负整数,故选-1.修改后如下:
Long userId = UserUtil.getLoginUserId(request);
if(userId == null){
userId = -1L;
}