• mybatis中if判断为0无效


    问题描述

    下面sql语句中,level字段传入0的时候,插入和修改都会失败。

    	<update id="updateDept" parameterType="SysDept">
     		update sys_dept
     		<set>
     			<if test="parentId != null and parentId != 0">parent_id = #{parentId},if>
     			<if test="deptName != null and deptName != ''">dept_name = #{deptName},if>
     			<if test="ancestors != null and ancestors != ''">ancestors = #{ancestors},if>
     			<if test="orderNum != null">order_num = #{orderNum},if>
     			<if test="leader != null">leader = #{leader},if>
     			<if test="phone != null">phone = #{phone},if>
     			<if test="email != null">email = #{email},if>
     			<if test="status != null and status != ''">status = #{status},if>
     			<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},if>
    			<if test="level != null and level != ''">level = #{level},if>
     			update_time = sysdate()
     		set>
     		where dept_id = #{deptId}
    	update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    原因与方案

    mybatis中传入int类型的0时,会当成字符处理,即当成""空字符串处理。如果要插入0 ,把后面level != ''删掉即可,只留下面面的判断。
    修改后的level字段如下:

    	<update id="updateDept" parameterType="SysDept">
     		update sys_dept
     		<set>
     			<if test="parentId != null and parentId != 0">parent_id = #{parentId},if>
     			<if test="deptName != null and deptName != ''">dept_name = #{deptName},if>
     			<if test="ancestors != null and ancestors != ''">ancestors = #{ancestors},if>
     			<if test="orderNum != null">order_num = #{orderNum},if>
     			<if test="leader != null">leader = #{leader},if>
     			<if test="phone != null">phone = #{phone},if>
     			<if test="email != null">email = #{email},if>
     			<if test="status != null and status != ''">status = #{status},if>
     			<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},if>
    			<if test="level != null">level = #{level},if>
     			update_time = sysdate()
     		set>
     		where dept_id = #{deptId}
    	update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 相关阅读:
    SQL 语言数据操纵语言 DML
    算法篇-----回溯1
    Detecting Topic Authoritative Social Media Users: a Multilayer Network Approach
    SpringCloud 学习(一)---- 微服务的概念
    minio文件上传
    Python:【基础语法】 deque()用法
    mysql InnoDB 事务的实现原理
    SpringBoot中优雅地实现统一响应对象
    力扣每日一题64:最小路径和
    双软认证的条件和优惠政策?
  • 原文地址:https://blog.csdn.net/ITzhongzi/article/details/126320777