Mybatis中where标签与if标签怎么结合使用

免费教程   2024年05月10日 2:19  

这篇文章主要介绍“Mybatis中where标签与if标签怎么结合使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Mybatis中where标签与if标签怎么结合使用”文章能帮助大家解决问题。

使用<where>标签

select筛选出视图对象的参数,用于给前端返回页面参数使用。

<sqlid="selectFileVo">selectfile_id,uuid,file_name,file_url,status,create_time,update_timefromfile</sql>

以下代码格式是正确,我们先观察下and或者or的位置。

<selectid="selectFileList"parameterType="File"resultMap="FileResult"><includerefid="selectFileVo"/><where><iftest="fileName!=nullandfileName!=''">andfile_namelikeconcat('%',#{fileName},'%')</if><iftest="status!=nullandstatus!=''">andstatus=#{status}</if><iftest="params.beginCreateTime!=nullandparams.beginCreateTime!=''andparams.endCreateTime!=nullandparams.endCreateTime!=''">andcreate_timebetween#{params.beginCreateTime}and#{params.endCreateTime}</if></where></select>

再看一下错误的写法;

<selectid="selectFileList"parameterType="File"resultMap="FileResult"><includerefid="selectFileVo"/><where><iftest="fileName!=nullandfileName!=''">file_namelikeconcat('%',#{fileName},'%')and</if><iftest="status!=nullandstatus!=''">status=#{status}and</if><iftest="params.beginCreateTime!=nullandparams.beginCreateTime!=''andparams.endCreateTime!=nullandparams.endCreateTime!=''">create_timebetween#{params.beginCreateTime}and#{params.endCreateTime}</if></where></select>

这时候运行该代码,当beginCreateTime或endCreateTime为空时,我们会发现报错SQL执行异常,原因是where多了一个and。

总结

当<if>标签判断失败后, <where> 标签关键字可以自动去除掉库表字段赋值前面的and,不会去掉语句后面的and关键字,即<where> 标签只会去掉<if> 标签语句中的最开始的and关键字。所以上面的写法(and写在后面)是不符合mybatis规范的。

不使用<where>标签

当不使用<where>标签时,正确的写法可以参考以下代码:

<selectid="selectFileList"parameterType="File"resultMap="FileResult"><includerefid="selectFileVo"/>where1=1<iftest="fileName!=nullandfileName!=''">andfile_namelikeconcat('%',#{fileName},'%')</if><iftest="status!=nullandstatus!=''">andstatus=#{status}</if><iftest="params.beginCreateTime!=nullandparams.beginCreateTime!=''andparams.endCreateTime!=nullandparams.endCreateTime!=''">andcreate_timebetween#{params.beginCreateTime}and#{params.endCreateTime}</if></select>

此时我们发现and是写在前面的,同时增加了1=1条件。

如果我们去掉1=1条件,同时去掉第一个<if>标签的and。

<selectid="selectFileList"parameterType="File"resultMap="FileResult"><includerefid="selectFileVo"/>where<iftest="fileName!=nullandfileName!=''">file_namelikeconcat('%',#{fileName},'%')</if><iftest="status!=nullandstatus!=''">andstatus=#{status}</if><iftest="params.beginCreateTime!=nullandparams.beginCreateTime!=''andparams.endCreateTime!=nullandparams.endCreateTime!=''">andcreate_timebetween#{params.beginCreateTime}and#{params.endCreateTime}</if></select>

这种情况下,当fileName为空时,sql语句中会出现where and这种错误的语法,最终导致sql执行异常。所以正确的代码中,使用1=1条件,当fileName为空时,sql语句就会变成where 1=1 ,后面接不接and都能正确执行。

在不使用<where>标签的情况下,and写在后面,在where条件最后增加1=1判断,原理和上面一样,这里就不再赘述了。

关于“Mybatis中where标签与if标签怎么结合使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注行业资讯频道,小编每天都会为大家更新不同的知识点。

域名注册
购买VPS主机

您或许对下面这些文章有兴趣:                    本月吐槽辛苦排行榜

看贴要回贴有N种理由!看帖不回贴的后果你懂得的!


评论内容 (*必填):
(Ctrl + Enter提交)   

部落快速搜索栏

各类专题梳理

网站导航栏

X
返回顶部