动态SQL

1.if

1
2
3
4
5
6
7
8
9
10
11
<select id="getBlog" parameterType="map" resultType="com.saxon.pojo.Blog">
select * from mybatis.blog
<where>
<if test="views!=null">
and views>#{views}
</if>
<if test="title!=null">
and title =#{title}
</if>
</where>
</select>

if就是一个判断语句,我们的条件满足时将sql拼接上去。使用where标签时,如果是第一个条件,那么就会把开头的and或者or删除,在拼接;

2.choose、when、otherwise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<select id="getBlog" parameterType="map" resultType="com.saxon.pojo.Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
author=#{author}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</where>
</select>

choose语句相当于Java中的switch语句,那么when就是case标签,otherwise就是default标签,这个拼接和顺序有关,如果我们的条件都成立的话,那么就会只走第一个,相当于switch里面的条件成立就会break一样

3.set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<update id="update" parameterType="map">
update mybatis.blog
<set>
<if test="author!=null">
author=#{author},
</if>
<if test="title!=null">
title=#{title}
</if>
</set>
<where>
id=#{id}
</where>
</update>

用于数据库的更新,set会自动帮我们去掉只有一句的时候的句末的逗号和最后一句的句末的逗号==需要注意的是,你如果没有加上的话,他是不会自动帮你添加的==

4.sql字段

将一段可能复用的代码进行一个复用;

1
2
3
4
5
6
7
8
9
10
11
12
13
<sql id="sql_title_author">
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
author=#{author}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</sql>
1
2
3
4
5
6
<select id="getBlog" parameterType="map" resultType="com.saxon.pojo.Blog">
select * from mybatis.blog
<where>
<include refid="sql_title_author"/>
</where>
</select>
  • sql片段不要使用过于复杂的语句,这样会降低代码的复用性
  • 在代码片段里面不要加上where,set等,不然会让代码复用性降低

5.foreach

1
2
3
4
5
6
7
8
<select id="getBlog" parameterType="map" resultType="com.saxon.pojo.Blog">
select * from mybatis.blog
<where>
<foreach collection="views" open="(" separator="or" close=")" item="views">
views=#{views}
</foreach>
</where>
</select>

里面的open,close和separator 构成拼接sql语句 item是集合中遍历的元素 collection表示的属性的名字,就是你放在map集合里面key的值,views=#{views}是拼接语句的内容,每一句之间用or隔开

下面就是拼接后的字符串:

1
select * from mybatis.blog WHERE ( views=? or views=? )