怎么建设网站网页游戏湖南正规seo公司
目录
一、背景
二、if标签
三、trim标签
四、where标签
五、set标签
六、foreach标签
一、背景
如果我们要执行的SQL语句中不确定有哪些参数,此时我们如果使用传统的就必须列举所有的可能通过判断分支来解决这种问题,显示这是十分繁琐的。在SpringBoot中整合MyBatis的xml文件中,我们可以使用动态SQL来完成操作
二、if标签
语法:<if test="参数!=null">
……
</if>
其中test会产生一个boolean类型结果,如果返回ture则执行标签里的东西,如果false则不
如果有一个用户信息表,我们在插入时不确定用户是不是会传入Email这个字段时,我们可以通过if标签进行处理
<select id="updateInfo" returnType="com.example.demo.model.User">insert into user(username,password,<if test="email != null">email,</if>ip) value(#{username},#{password},<if test="email != null">#{email},</if>#{ip})</select>
if标签逗号问题
比如此时我们需要修改用户的信息,但是我们不知道用户修改了哪些信息时,我们就可以使用if标签
<update id="updateInfo">update userinfo set<if test="username != null">username=#{username},</if><if test="nickname != null">nickname=#{nickname},</if><if test="password != null">password=#{password},</if><if test="photo != null">photo=#{photo}</if><if test="email != null">,email=#{email}</if>where id=#{id}</update>
要注意如果存在时拼接时的逗号问题,比如上述修改sql在最后一个判断修改时把逗号写在了后面,此时Email这个参数不为空则sql是update userinfo set email='', where id=1则会出错,上述代码仅展示if标签的使用,存在逗号问题,后面会有提到更优的解决方案
三、trim标签
语法------trim标签的四个属性
suffixOverrides:把最后一个关键字去掉,有则去没则不去掉
suffix:后缀
prefix:前缀
prefixOverrides:把最前面的一个关键字去掉,有则去没则不去掉
此时我们就可以利用suffixOverrides这个属性来解决逗号问题了,下面是一个插入案例
<insert id="add">insert into userinfo<trim prefix="(" suffix=")" suffixOverrides=","><if test="username != null">username,</if><if test="password != null">password,</if></trim><trim prefix="(" suffix=")" suffixOverrides=","><if test="username != null">#{username},</if><if test="password != null">#{password},</if></trim></insert>
四、where标签
语法:
将查询语句中的where关键字使用该标签代替,通常与if标签搭配使用,它比传统的SQL中的关键字where优势是,如果所有的查询条件都没有则最终生成SQL语句时不生成没有条件的where,它会将紧跟这where的标签的第一个and删除比如where and会将and删除
使用where标签进行查询时
<select id="" returnType=""">select * from userinfo <where><if test"username != null">username=#{username}</if><if test"id != null">and id=#{id}</if></where>
</select>
五、set标签
语法:
与where类似,通常搭配if使用,set主要用于修改操作,where是去掉前面的and,,而set是去掉最后一个逗号
<update id="">update userinfo<set><if test="username!=null"> set username=#{username}, </if><if test="password!=null"> set password=#{password}, </if></set>where id=#{id}
</update>
六、foreach标签
语法:
他的几个属性
collection:传回数据的集合
item:每次遍历的值,类似Java循环中的i变量
open:前缀
close:后缀
separator:每个变量之间的分隔符
<delete>delete from userinfo where id in<foreach collection=“接口集合变量名" open"(" close") separator="," item="item">#{item}</foreach>
<delete>
上述这段代码如果传参是list={1,2,3,4}则上述代码等效于
delet from userinfo where id=(1,2,3,4)