一、MyBatis動态語句分為4種元素:
元素 | 作用 | 描述 |
if | 條件判斷 | 單條件判斷 |
choose(when、otherwise) | 條件選擇,相當Java when | 多條件分支判斷 |
where、set | 輔助 | 處理sql語句拼接問題 |
foreache | 循環 | 循環 |
二、Mybatis動态sql語句使用方式、例子
1、if元素,如下
<select id="selByName" resultType="yuan.yuanmybatis.entity.Account">
select id,name,created,updated from account where 1=1
<if test="name !=null and name !=''">
and name like concat('%',#{name},'%')
</if>
</select>
2.choose
<select id="selByChoose" resultType="yuan.yuanmybatis.entity.Account">
select id,name,created,updated,money from account where 1=1
<choose>
<when test="name !=null and name !=''">
and name like concat('%',#{name},'%')
</when>
<when test="money !=null and money !=''">
and name =#{money}
</when>
<otherwise>
and isdeleted=1
</otherwise>
</choose>
</select>
3、where元素,細心的讀者會發現1、2點會有一個1=1,如果沒有1=1,那麼會變成如下錯誤語句:
select id,name,created,updated,money from account where and name like concat('%',#{name},'%')
這個時候我們可以用where元素處理sql:
<select id="selByName" resultType="yuan.yuanmybatis.entity.Account">
select id,name,created,updated from account
<where>
<if test="name !=null and name !=''">
and name like concat('%',#{name},'%')
</if>
</where>
</select>
where元素在裡面的條件成立的時候,才會加入where這個sql關鍵字。
4、trim元素可以幫助我們去掉一下and、or等,prefix代表語句字首, prefixOverrides代表要去掉的字元串
<select id="selByChoose" resultType="yuan.yuanmybatis.entity.Account">
select id,name,created,updated,money from account
<trim prefix="where" prefixOverrides="and">
<choose>
<when test="name !=null and name !=''">
and name like concat('%',#{name},'%')
</when>
<when test="money !=null and money !=''">
and name =#{money}
</when>
<otherwise>
and isdeleted=1
</otherwise>
</choose>
</trim>
</select>
5、set元素,它可以在遇到逗号的時候,把對應的逗号去掉
<update id="updateAccout" parameterType="yuan.yuanmybatis.entity.Account">
update account
<set>
<if test="name !=null and name !=''">
name=#{name},
</if>
<if test="money!=null and money!=''">
money=#{money}
</if>
</set>
where id=#{id}
</update>
6、foreach元素,它時一個循環語句,作用時用來周遊集合,支援數組、List、Set接口集合
<select id="selIn" resultType="yuan.yuanmybatis.entity.Account">
select id,name,created,updated from account where name in
<foreach collection="nameList" index="index" item="name" open="(" separator="," close=")">
#{name}
</foreach>
</select>