博主是一个刚刚毕业的靓仔,也是一个刚刚入门的程序猴
mybatis中的if标签
公司的项目中dao层用的是mybatis,数据库用的mysql,在写查询的时候用到了if这个标签,通常if标签我们都是这样用的
<where>
<if test="dbid!=null and dbid!=''">
and dbid=#{dbid}
</if>
<if test="metricCatagory!=null and metricCatagory!=''">
and metric_catagory=#{metricCatagory}
</if>
<if test="metricName!=null and metricName!=''">
and metric_name=#{metricName}
</if>
<if test="alertLevel!=null and alertLevel!=''">
and alert_level=#{alertLevel}
</if>
<if test="start!=null and end!=null">
and alert_date between #{start} and #{end}
</if>
</where>
表面上看没有什么问题,但是这里面有一个字段是Integer类型的,就是alertLevel这个字段,如果可能等于0,这里的判断就不能那样写
第一种写法:
<if test="alertLevel!=null and alertLevel!==0">
and alert_level=#{alertLevel}
</if>
第二种写法:
<if test="(alertLevel!=null and alertLevel!='') or alertLevel==0">
and alert_level=#{alertLevel}
</if>
原因
Integer类型的数据如果在这里写成alertLevel!=’ ',那么mybatis在进行判断的时候会把它当成字符串判断,会返回空字符串的长度,也就是0,这里就变成了0!=0,那么肯定是false,自然判断不通过,这里的源码我没有看,因为鄙人是个初级入门的菜鸡,暂时还没能力去看。
更多推荐