1. 程式人生 > 實用技巧 >choose和bind

choose和bind

choose 標籤相當於程式語言 if…else 語句,用於動態 SQL 中的多條件判斷,是 if 標籤的增強版。
bind 標籤可以在動態 SQL 中通過 OGNL 表示式來建立一個新的變數繫結到上下文中,供後續的 SQL 使用。

<select id="selectUserByLikeName" resultType="com.imooc.mybatis.model.User">
  SELECT * FROM imooc_user
  WHERE username LIKE
  <choose>
    <when test="_databaseId == 'mysql'">
      CONCAT('%',#{username},'%')
    </when>
    <when test="_databaseId == 'postgre'">
      '%' || #{username} || '%'
    </when>
    <otherwise>
      <bind name="usernameLike" value="'%' + username + '%'"/>
      #{usernameLike}
    </otherwise>
  </choose>
</select>

通過choose標籤來判斷當前的資料庫廠商,如果是MySQL資料庫,則呼叫CONCAT函式來拼接% 和 username,如果是 PostgreSQL 資料庫,則使用操作符||來拼接,如果是其它型別的資料庫,則直接通過 OGNL 表示式來繫結一個新的變數 usernameLike。

在這個例子中,choose 是一個條件選擇標籤,第一個 when 相當於 if 判斷,第二個 when 相當於 else if,最後的 otherwise 相當於 else。比起 if 標籤,choose 標籤無疑更為易用,適用於同一條件的多次判斷邏輯。

Bind

使用 bind 標籤將引數小寫化成一個新的變數 lowercaseName。

<select id="selectUsernameLowercase" resultType="com.imooc.mybatis.model.User">
  <bind name="lowercaseName" value="username.toLowercase"/>
  SELECT * FROM imooc_user
  WHERE username = #{lowercaseName}
</select>