mybatis if test 不为空字符串且不为null的问题

2022-07-16,,,,

if test不为空字符串且不为null

mybatis中if test 

判断不为空字串和null的时候,报了sql 语法错误

xml文件:

where enable =1
<if test="keyword != null and keyword != ''">
        and ( mac_id = #{keyword} )
        or ( user_id = #{keyword} )
 </if>

postman工具报错如下:

原因:

if 判断中, 出现字母大小写错误, 不符合mybatis 语法规范

在mybatis中, if test 语法

1 判断不为null

where 1=1
<if test="keyword != null ">
        and  user_id = #{keyword} 
</if>

2 判断不为空字符串

where 1=1
<if test="keyword != '' ">
        and  user_id = #{keyword} 
</if>

3 判断不为null 且 不为空字符串

where 1=1
<if test="keyword != null and keyword != ''">
        and  user_id = #{keyword} 
</if>

controller层 —> 对应xml 文件

我们在获取列表时,通常会根据关键词进行精确或模糊查询,就会对关键词进行非空或者非null的判断。如下:

controller层请求参数keyword 请求参数默认值 dao层xml 文件
@requestparam(value = “keyword”, required = false) string keyword null if test="keyword != null "
@requestparam(value = “keyword”, required = false, defaultvalue = “”) string keyword 空字符串 if test="keyword != ‘’ "
/ 不清楚默认值 都可以if test=“keyword != null and keyword != ‘’”
参数 默认值 dao层xml 文件
从其他渠道的获取的数据或关键词 不清楚默认值 if test=“keyword != null and keyword != ‘’”

mybatis把0当做空字符串

在开发中,一般在sqlmap中都会判断参数是否为null,以及是否为空字符串

当参数为int类型 0时,mybatis自动把0定义为空字符串“”

我们在可能入参为0的地方多加一个判断

 <if test="authorizeamount != null and ''!= authorizeamount or authorizeamount==0">
            ,a.authorize_amount = #{authorizeamount,jdbctype=varchar}
        </if>

这是一个比较容易粗心的地方,出问题也不容易排查,记录下来提醒自己!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

《mybatis if test 不为空字符串且不为null的问题.doc》

下载本文的Word格式文档,以方便收藏与打印。