记录常用的mybatis中动态SQL的标签
1.if
当需要动态生成where条件时,可以使用if标签:
<select id="find" resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null and title != ''">
AND title like #{title}
</if>
</select>
2.choose, when, otherwise
当需要从多个条件中选择一项时,可以使用choose元素:
<select id="find" resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
3.where
当where条件中都需要动态生成,可以使用where标签,自动去除多余的 AND 或者 OR 关键字:
<select id="find" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
4. set
与where标签相似,在update的时候,可以自动去除多余的逗号:
<update id="update">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password}</if>
</set>
where id=#{id}
</update>
5.trim
where 和 set 都是通过 trim 来实现的:
<trim prefix="WHERE" prefixOverrides="AND|OR ">
...
</trim>
<trim prefix="SET" suffixOverrides=",">
...
</trim>
比如,Where标签可以用trim代替为:
<trim prefix="WHERE" prefixOverrides="AND">
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</trim>
prefix 代表前缀,会插入到生成的条件前面,prefixOverrides 代表去除前缀, suffixOverrides 代表去除后缀,多个参数可以用管道符 "|" 分割
6.foreach
对一个集合进行遍历,通常是在构建 IN 条件语句的时候:
<select id="select" resultType="domain.blog.Post">
SELECT * FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。
注意 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数。当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
7.sql和include
sql标签用来编写可重用的sql语句:
<sql id="query_user_where">
<if test="id!=null and id!=''">
and id=#{id}
</if>
<if test="username!=null and username!=''">
and username like '%${username}%'
</if>
</sql>
<include>标签用来引入<sql>中定义的代码片:
<select id="findUserList" parameterType="user" resultType="user">
select * from user
<where>
<include refid="query_user_where"/>
</where>
</select>
也可以引用其他mapper.xml文件中的代码片:
<include refid="namespace.sql片段"/>