动态SQL if和where标签在Mybatis中的语法
如果我们需要拼接where条件,又不希望客户端传递的错误信息,需要更加智能的where标签如果有后面的语句,就自动添加where,并且如果后面的语句开头是and or 它可以自动去掉
<where>
<if test=" ">
判断的内容
</if>
</where>
set标签
set标签重点注意后面的逗号
前几个需要逗号最后一个不需要逗号
set标签如果里面的条件满足,会自动拼接Set标签,后面如果有逗号会自动去处。
<update id="updateBlog" parameterType="map">
update blog <set>
<if test="title!=null">title=#{title},</if>
<if test="author!=null"> author=#{author}</if>
</set>
where id=#{id};
</update>
choose好比switch标签
有时候我们不想用所有的条件语句,而只想从中选择一项,针对这种情况,选择choose元素
<select id="selectBlog" resultType="Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
foreach
sql()子查询where in (1,2,3)
collection输入的参数map中的名字
item遍历出来的每一项
通过item遍历出的参数可以在foreach标签中使用
select * from mybatis.blog;
<foreach collection="ids" item="id" open="and(" close=")" separator="or">
id=#{id}
</foreach>
本文深入探讨MyBatis框架中动态SQL的高级应用,包括if、where、set、choose和foreach标签的语法与实践。解析如何根据条件智能生成SQL语句,避免SQL注入风险,提升数据库操作效率。
2292

被折叠的 条评论
为什么被折叠?



