if & where
动态SQL通常要做的事情就是根据条件包含where子句的一部分
<select id="findUserByUsernameAndSex"
parameterType="Demo01.pojo.User" resultType="Demo01.pojo.User">
select * from `user`
where 1=1
<if test="username !=null and username!='' ">
and username like '%${username}%'
</if>
<if test="sex!=null and sex!='' ">
and sex=#{sex}
</if>
</select>
可以封装SQL后重用
- id:这个SQL语句的唯一标识
- where元素:只会在至少一个子元素的条件返回SQL子句的情况下才会去插入
WHERE
子句;而且,若语句开头为AND
或OR
,where元素也会将它们去除
<!-- 封装SQL -->
<sql id="user_Where">
<where>
<if test="username != null and uername != '' ">
and username like '%${username}%'
</if>
<if test="sex != null and sex!='' ">
and sex=#{sex}
</if>
</where>
</sql>
<!-- 调用SQL namespace.sql片段 -->
<select id="findUserByUsernameAndSex"
parameterType="Demo01.pojo.User" resultType="Demo01.pojo.User">
select * from `user`
<include refid="user_Where"/>
</select>
set
set元素会动态前置SET
关键字,同时也会删除无关的逗号,因为使用条件语句之后很可能就会在生成的SQL语句的后面留下这些逗号
<update id="updateAuthor">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
foreach & 拼接
foreach元素允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。当使用可迭代对象或数组时,index是当前的迭代次数,item的值是本次迭代获取的元素,当使用Map对象时候,index是键,item是值。
<!-- 原来的SQL语句 -->
select * from `user` where id in (1,16,28)
<!-- foreach SQL语句 -->
<select id="findUserByIds" parameterType="Demo01.pojo.QueryVo" resultType="Demo01.pojo.User">
select * from `user`
<where>
<if test="ids != null">
<foreach collection="ids" item="id" open="id in (" close=")" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
关键点:
- foreach:循环传入的集合参数
- collection:传入的集合名称
- item:每次循环将循环出的数据放入这个变量中
- open:循环开始拼接的字符串
- close:循环结束拼接的字符串
- separator:循环拼接的分隔符
下一篇:Mybatis学习笔记[6] 之关联查询 https://blog.youkuaiyun.com/Rabbit_Judy/article/details/80849369