III-MyBatis 動態sql語句

mybatis 的動態sql語句是基於OGNL表達式的。 分如下幾類:java

1. if 語句 (簡單的條件判斷)
<if test="itemOid != null">
    item_oid = #{itemOid}
</if> //item_oid 爲表的列名,itemOid爲傳入參數的屬性名
2. choose (when,otherwize) ,至關於java 語言中的 switch ,與 jstl 中的choose 很相似.(全部的when和otherwise條件中,只有一個會輸出)
<choose>
  <when test="title != null">
        and title = #{title}
  </when>
  <when test="content != null">
        and content = #{content}
  </when>
  <otherwise>
        and owner = "owner1"
  </otherwise>
</choose>
3. trim (對包含的內容加上 prefix,或者 suffix 等,前綴,後綴)
<trim prefix="where" prefixOverrides="and |or" suffix="">
</trim>
4. where (主要是用來簡化sql語句中where條件判斷的,能智能的處理 and or ,沒必要擔憂多餘致使語法錯誤)
<where>
    <if test="title != null">
        and title = #{title}
	</if>
    <if test="content != null">
        and content = #{content}
    </if>
</where>
5. set (主要用於更新時)
<set>
    <if test="title != null">
        title = #{title},
    </if>
    <if test="content != null">
        content = #{content},
    </if>
    <if test="owner != null">
        owner = #{owner}
    </if>
</set>
6. foreach (在實現 mybatis in 語句查詢時特別有用)
where id in
<foreach collection="list" index="index" item="temp" open="(" separator="," close=")">
    #{temp}
</foreach>
相關文章
相關標籤/搜索