Mybatis-動態SQL-查詢與更新

查詢經常使用到<if><choose><when><otherwise><trim>標籤,他們都支持ognl表達式
--|<if> 條件判斷和Java中if同樣,如sql

<if test="id!=null and id!=''">

--|<choose>就像Java的帶有break的switch,搭配<when><otherwise>使用
----|<when>當條件知足是執行拼接其中的內容,如ide

<when test="custId!=null and custId%2==0" >
				concat(cust_name,'_aa') cust_name
			</when>

----|<otherwise>當全部<when>都不知足,則拼接它的內容,如code

<otherwise>
				concat(cust_name,'_bb') cust_name
			</otherwise>

一個完整的查詢例子配置:xml

<!-- 複雜查詢,使用if choose 標籤 -->
	<select id="getCustsByCust" resultType="com.jv.dynamic.bean.Cust">
		select cust_id,
		<choose>
			<when test="custId!=null and custId%2==0" >
				concat(cust_name,'_aa') cust_name
			</when>
			<otherwise>
				concat(cust_name,'_bb') cust_name
			</otherwise>
		</choose>
		from cust
		<where>
			<!-- ognl表達式還支持&&等操做符,可是在xml中須要使用其轉義字符
				好比:<if test="custId!=null!=null &amp;&amp; custId!=null!=&quot;&quot;">
				其中&amp;是表明&符號;&quot;表明雙引號
				
				爲了閱讀方便,推薦使用肺轉移符
			-->
			<if test="custId!=null and custId!=''">
				cust_id=#{custId}
			</if>
			<if test="custName!=null and custName!=''">
				and cust_name like #{custName}
			</if>
		</where>
	</select>

在實際項目開發中,有的公司或者開發人員喜歡不使用<where>標籤,而是直接寫"where 1=1",後面全部的條件判斷對應的SQL都是"and"開頭,這種寫法也討巧,思路靈活。開發

而爲何使用<where>標籤喃,由於Mybatis能夠幫助咱們若是把「and」寫在開頭的狀況下,不出現拼接完成sql出現where and column_name = ?的狀況。若是把「and」寫在最後,<where>標籤也就沒有用了,不過能夠使用<trim>標籤,好比:get

<trim suffixOverrides="">
            <if test="custId!=null and custId!=''">
				cust_id=#{custId} and
			</if>
			<if test="custName!=null and custName!=''">
				cust_name like #{custName}
			</if>
         </trim>


更新經常使用到<set>標籤it

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>
相關文章
相關標籤/搜索