簡單總結一下。
1、if。類似於java中if。test中寫條件
select * from user
where 1=1
<if test="sex !=null and sex!=''">
and sex =#{sex}
</if>
<if test="username !=null and username !=''">
and username like '%${username}%'
</if>
2、where。mysql中的添加查詢條件。可以自動去除一個and、or關鍵詞
select * from user
<where>
<if test="sex !=null and sex!=''">
and sex =#{sex}
</if>
<if test="username !=null and username !=''">
and username like '%${username}%'
</if>
</where>
3、foreach。循環。
separator:遍歷對象之間需要拼接的字符串
open:拼接開頭部分。
close:拼接結束部分。
collection:循環的集合
item:每次遍歷生成的對象
select * from user
<where>
id in
<foreach collection="idList" separator="," open="(" close=")"
item="id">
#{id}
</foreach>
</where>
<!-- 最後輸出形式
select * from user WHERE id in ( ? , ? , ? )
-->
4、sql。sql片段
有時候一個判斷或其他sql多次用到,爲了增加代碼重用行,簡化代碼。添加一個代碼片段。其他地方可以直接調用。
<sql id="sexV">
<if test="sex !=null and sex!=''">
and sex =#{sex}
</if>
</sql>
select * from user
<where>
<include refid="sexV"></include>
<if test="username !=null and username !=''">
and username like '%${username}%'
</if>
</where>
5、choose(when,otherwise) 語句
有時候我們只想用很多條件中的一個,滿足一個條件即可。類似於java的switch。
select * from user
<where>
<choose>
<when test="username !=null and username !=''">
and username like '%${username}%'
</when>
<when test="sex !=null and sex!=''">
and sex =#{sex}
</when>
<otherwise>
and id=#{id}
</otherwise>
</choose>
</where>
6、set 語句
在做更新操作時。
update user
<set>
<if test="username != null and username != ''">
u.username = #{username},
</if>
<if test="sex != null and sex != ''">
u.sex = #{sex}
</if>
</set>
where id=#{id}
7、trim(where,set)標籤
prefix:前綴
prefixoverride:去掉第一個and或者是or。
suffix:後綴
suffixoverride:去掉最後一個逗號(也可以是其他的標記,就像是上面前綴中的and一樣)
select * from user
<!--
<where>
<include refid="sexV"></include>
<if test="username !=null and username !=''">
and username like '%${username}%'
</if>
</where>
-->
<trim prefix="where" prefixOverrides="and | or ">
<include refid="sexV"></include>
<if test="username !=null and username !=''">
and username like '%${username}%'
</if>
</trim>