记一次mybatis 标签嵌套使用失效问题

12 4 月, 2024 198点热度 0人点赞 0条评论

在最近的一次功能开发中,在通过使用Mybatis进行SQL拼接的时候,由于if条件比较复杂,因此使用了if的嵌套使用,具体的传参和mapper SQL如下图:

<if test="operatorType != null and operatorType != ''">
    <if test="operatorType=='3'">
        and a.operator_type = #{operatorType}
        <if test="operatorId != null and operatorId != ''">
            and a.operator_id = #{operatorId}
        </if>
    </if>
    <if test="operatorType=='1'">
        and a.depart_id = #{departId}
    </if>
</if>

在请求查询的时候,发现传入了operatorType的参数,最终也会导致if中的SQL没有被正确解析,因此做如下修改:

<if test='operatorType != null and operatorType != ""'>
    <if test='operatorType=="3"'>
        and a.operator_type = #{operatorType}
        <if test='operatorId != null and operatorId != ""'>
            and a.operator_id = #{operatorId}
        </if>
    </if>
    <if test='operatorType=="1"'>
        and a.depart_id = #{departId}
    </if>
</if>

再次执行的时候,发现被正确的执行了。

这里我猜测是因为在做字符串的比较的时候,mybatis将单个的字符串当做char来对象,导致在进行规则判断的时候失败了

如果你知道具体原因,希望能够在评论区流程,大家互相交流一下。

 

专注着

一个奋斗在编程路上的小伙

文章评论