WHERE标签
- 应用场景:
where元素只会在至少有一个子元素的条件返回sql子句的情况下才去插入where子句,而且,若语句开头为and或or,where元素也会将他们去除。
”面向百度编程“
下面来看一下where标签的强大之处 - BlogMapper8.xml
<where>
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</where>
-
情况一:
where标签后面没有条件,此时会省略where,等同于无条件查询
-
情况二:
where标签后面跟的第一个条件的and会自动被省略 执行如下
测试:
map.put("title","2");
执行如下:
- 第三种情况
有一个and,但不是在开头时候,where会执行。
HashMap map = new HashMap<>();
map.put("title","2");
map.put("author","1");
choose
如果第一个满足,不管后面满不满足,都会输出
<select id="queryBlogChoose" parameterType="map" 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>
Set
自动去除逗号
- 更新操作
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author}
</if>
</set>
where id=#{id}
</update>
trim
所谓的动态sql ,本质还是sql , 只是可以在sql层面去执行一些逻辑代码。
没讲到,只是提到trim是choose,set的父类。