Mybatis if判断字符串遇到的坑

文章讲述了在MyBatis的xml文件中,针对status为char类型时,如何根据前端传入的不同字符串值正确执行SQL查询。通过使用status.toString()转换解决因字符类型导致的拼接错误。
摘要由CSDN通过智能技术生成

1,数据库status字段为char(1)  

2,mybatis.xml要根据status的值做处理

 <if test="status != null and status !='' ">
            <choose>
                <!-- 如果传入的status是0,查询status为0或1的数据 -->
                <when test="status == '0'">
                    AND pa.status IN ('0', '1')
                </when>
                <when test="status == '1'">
                    AND pa.status IN ('0', '1')
                </when>
                <!-- 如果传入的status是2、3、4,直接使用等于条件 -->
                <when test="status == '2' or status == '5' or status == '4'">
                    AND pa.status = #{status}
                </when>
                <!-- 其他情况,可以选择不添加任何条件,或者根据需要添加默认行为 -->
                <otherwise>
                    AND pa.status = '5'
                    <!-- 这里可以留空,或者添加你认为合适的默认SQL条件 -->
                </otherwise>
            </choose>
</if>

3, 这种情况,前端传参为字符串"0"会出现拼接pa.status='5'  前端传参字符串"2"会拼接pa.status='5'  前端传参字符串"1"会拼接pa.status='5'  

4,解决办法

 <if test="status != null and status !=''.toString() ">
            <choose>
                <!-- 如果传入的status是0,查询status为0或1的数据 -->
                <when test="status == '0'.toString()">
                    AND pa.status IN ('0', '1')
                </when>
                <when test="status == '1'.toString()">
                    AND pa.status IN ('0', '1')
                </when>
                <!-- 如果传入的status是2、3、4,直接使用等于条件 -->
                <when test="status == '2'.toString() or status == '5'.toString() or status == '4'.toString()">
                    AND pa.status = #{status}
                </when>
                <!-- 其他情况,可以选择不添加任何条件,或者根据需要添加默认行为 -->
                <otherwise>
                    AND pa.status = '5'
                    <!-- 这里可以留空,或者添加你认为合适的默认SQL条件 -->
                </otherwise>
            </choose>
</if>

5,虽然toStirng()绝大数情况都不需要加,但不知道为什么Char比较特殊,查资料无果,故记录。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值