當數組遇到mybatis in 的時候

我想實現  “多個id 傳入sql 語句“的操作。

1、我試着將數組  stringUtils.join(數組,",");    //數組轉string 並以逗號分隔

      沒成功。因爲傳到sql 裏是“123,234,435” ,而我們需要的是“123”,“234”,“345” 這樣格式。

2、oracle   split string to table

      select * from table1 where  id  in   (select * from  table(str2table(#{ids},‘,’)));

     而 str2table可以這樣寫:

     

     CREATE OR REPLACE TYPE TY_OBJECT AS OBJECT(COL_NAME VARCHAR2(200));
/
CREATE OR REPLACE TYPE TY_TABLE AS TABLE OF TY_OBJECT;
/
CREATE OR REPLACE FUNCTION STR2TABLE(V_STR       IN VARCHAR2,
                                     V_DELIMITER IN VARCHAR2)
--此函數的目的是將以特定字符分隔的字符串轉換爲遊標形式,以例遍歷此遊標
 RETURN TY_TABLE AS
  V_TY_TABLE TY_TABLE;
BEGIN
  SELECT TY_OBJECT(REGEXP_SUBSTR(V_STR,
                                 '[^' || V_DELIMITER || ']+',
                                 1,
                                 LEVEL,
                                 'i'))
    BULK COLLECT
    INTO V_TY_TABLE
    FROM DUAL
  CONNECT BY LEVEL <=
             LENGTH(V_STR) -
             LENGTH(REGEXP_REPLACE(V_STR, '' || V_DELIMITER || '', '')) + 1;
  RETURN V_TY_TABLE;
END;


摘自:http://blog.csdn.net/e_wsq/article/details/52381846


這樣就能獲得“123”,“234”,“345”的格式



3、還可以用mybatis  自帶的  foreach 方法    

      

1. 當查詢的參數只有一個時 
  findByIds(List<Long> ids)
 1.a 如果參數的類型是List, 則在使用時,collection屬性要必須指定爲 list
複製代碼
 <select id="findByIdsMap" resultMap="BaseResultMap">
         Select
         <include refid="Base_Column_List" />
         from jria where ID in
                  <foreach item="item" index="index" collection="list" 
                         open="(" separator="," close=")">
                        #{item}
                </foreach>
  </select> 
複製代碼

 findByIds(Long[] ids)
 1.b 如果參數的類型是Array,則在使用時,collection屬性要必須指定爲 array
複製代碼
  <select id="findByIdsMap" resultMap="BaseResultMap">
                 select
                 <include refid="Base_Column_List" />
          from jria where ID in
                  <foreach item="item" index="index" collection="array" 
                         open="(" separator="," close=")">
                        #{item}
                </foreach>
  </select> 
複製代碼

2. 當查詢的參數有多個時,例如 findByIds(String name, Long[] ids)
 這種情況需要特別注意,在傳參數時,一定要改用Map方式, 這樣在collection屬性可以指定名稱
         下面是一個示例
複製代碼
         Map<String, Object> params = new HashMap<String, Object>(2);
        params.put("name", name);
         params.put("ids", ids);
        mapper.findByIdsMap(params);
 
 <select id="findByIdsMap" resultMap="BaseResultMap">
                 select
                 <include refid="Base_Column_List" />
          from jria where ID in
                  <foreach item="item" index="index" collection="ids" 
                         open="(" separator="," close=")">
                        #{item}
                </foreach>
   </select> 

    摘自:http://blog.csdn.net/jarniyy/article/details/51169242

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章