if test不为空字符串且不为null
在mybatis中if test
判断不为空字串和null的时候,报了sql 语法错误
xml文件:
1
2
3
4
5
|
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
1
2
3
4
|
WHERE 1=1 < if test = "keyword != null " > AND user_id = #{keyword} </ if > |
2 判断不为空字符串
1
2
3
4
|
WHERE 1=1 < if test = "keyword != '' " > AND user_id = #{keyword} </ if > |
3 判断不为null 且 不为空字符串
1
2
3
4
|
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的地方多加一个判断
1
2
3
|
< if test = "authorizeAmount != null and ''!= authorizeAmount or authorizeAmount==0" > ,a.AUTHORIZE_AMOUNT = #{authorizeAmount,jdbcType=VARCHAR} </ if > |
这是一个比较容易粗心的地方,出问题也不容易排查,记录下来提醒自己!
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/xinyuezitang/article/details/90238585