开发微信小程序“Java精选面试题”后台管理系统时,遇到根据状态判断是或否发布。
MySQL数据库中设计数据库表,其中某字段status使用tinyint数据类型,当修改状态的时候,赋值status属性的值为0,用于改变状态记录试题库中发布情况。
但是通过Debug模式查看Controller控制层明显已经获取到status等于0,但是在执行到MyBatis中xml文件SQL语句时,总是无法赋值成功,xml配置如下:
<update id="updateWarehouse" parameterType="Warehouse"> update t_warehouse <set> <if test="title != null and title != ''">title = #{title},</if> <if test="code != null and code != ''">code = #{code},</if> <if test="content != null and content != ''">content = #{content},</if> <if test="status != null and status != ''">status = #{status},</if> <if test="parentId != null and parentId != ''">parentId = #{parentId}</if> </set> where id = #{id} </update>
分析:
通过分析表面上没有任何传参问题,通过上网查询MyBatis相关资料,终于弄明白什么原因。
此行代码中
<if test="status != null and status != ''">status = #{status},</if>
and status != '',MyBatis中传参status的值为0时,因为数据类型为Integer类型,判断为false值。
MyBatis认定 0 = ''的,因此判断status != ''为false,这导致修改试题信息时状态值无法改变为0。
正确写法:
<update id="updateWarehouse" parameterType="Warehouse"> update t_warehouse <set> <if test="title != null and title != ''">title = #{title},</if> <if test="code != null and code != ''">code = #{code},</if> <if test="content != null and content != ''">content = #{content},</if> <if test="status != null">status = #{status},</if> <if test="parentId != null and parentId != ''">parentId = #{parentId}</if> </set> where id = #{id} </update>