1. if
根据条件添加或不添加sql语句,一般判断是否传递参数
<!--通过用户名或者id查询用户-->
<select id="getUserByUserCodeOrId" parameterType="map" resultType="User">
select * from smbms_user where id = #{id}
<if test="userCode != null">
and userCode = #{userCode}
</if>
</select>
注意:test中的变量名不需要加#{}
2. choose、when、otherwise
根据条件从多个sql语句中选择一个
<select id="getUserByUserCodeOrId" parameterType="map" resultType="User">
select * from smbms_user
<where>
<choose>
<when test="id != null">
id = #{id}
</when>
<when test="userCode != null">
userCode = #{userCode}
</when>
<otherwise>
userName = #{userName}
</otherwise>
</choose>
</where>
</select>
3. trim、where、set
3.1 where
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
3.2 set
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
3.3 trim
-
覆盖了前缀值设置,并且自定义了前缀值
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
-
覆盖了后缀值设置,并且自定义了前缀值
<trim prefix="SET" suffixOverrides=","> ... </trim>
4. foreach
- 对集合进行遍历(尤其是在构建 IN 条件语句的时候)
- 可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>