mybatis中foreach使用方法

foreach一共有三種類型,分別爲List,[](array),Map三種。java

foreach屬性

屬性 描述
item 循環體中的具體對象。支持屬性的點路徑訪問,如item.age,item.info.details。 具體說明:在list和數組中是其中的對象,在map中是value。 該參數爲必選。
collection 要作foreach的對象,做爲入參時,List<?>對象默認用list代替做爲鍵,數組對象有array代替做爲鍵,Map對象用map代替做爲鍵。 固然在做爲入參時可使用@Param("keyName")來設置鍵,設置keyName後,list,array,map將會失效。 除了入參這種狀況外,還有一種做爲參數對象的某個字段的時候。舉個例子: 若是User有屬性List ids。入參是User對象,那麼這個collection = "ids" 若是User有屬性Ids ids;其中Ids是個對象,Ids有個屬性List id;入參是User對象,那麼collection = "ids.id" 上面只是舉例,具體collection等於什麼,就看你想對那個元素作循環。 該參數爲必選。
separator 元素之間的分隔符,例如在in()的時候,separator=","會自動在元素中間用「,「隔開,避免手動輸入逗號致使sql錯誤,如in(1,2,)這樣。該參數可選。
open foreach代碼的開始符號,通常是(和close=")"合用。經常使用在in(),values()時。該參數可選。
close foreach代碼的關閉符號,通常是)和open="("合用。經常使用在in(),values()時。該參數可選。
index 在list和數組中,index是元素的序號,在map中,index是元素的key,該參數可選。

 

示例一:sql

<select id="countByUserList" resultType="_int" parameterType="list">
select count(*) from users
  <where>
    id in
    <foreach item="item" collection="list" separator="," open="(" close=")" index="">
      #{item.id, jdbcType=NUMERIC}
    </foreach>
  </where>
</select>

注:select count(*) from users WHERE id in ( ? , ? ) 數組

 

示例二:mybatis

    <select id="selectStorageProductInventroy" parameterType="java.util.Map" resultType="StorageProductInventroyModel">
        select op.inventroy_operation_id  ,
        op.inventroy_id  ,
        ty.name as operation_type,
        DATE_FORMAT(op.insert_time,'%Y/%m/%d') as insert_time,
        em.name as employee,
        sm1.name as from_store,
        st1.name as to_store,
        sm.name as from_storage,
        st.name as to_storage,
        hi.number,
        pr.name as product_name,
        pr.category_id as categoryString,
        pr.product_code,
        hi.amount,
        hi.back_amount,
        hi.unit,
        re.description as operation_reason,
        hi.description

        from inventroy_history hi  left join inventroy_operation  op 
        on hi.inventroy_operation_id = op.inventroy_operation_id
               
        left join product pr 
        on hi.product_id =pr.product_id
               
        left join operation_type ty 
        on op.operation_type_id = ty.operation_type_id
               
        left join employee em 
        on op.employee_id = em.employee_id
               
        left join   (select  inventroy_operation.to_storage_id as to_storage_id,storage.name as name
        from  inventroy_operation , storage
        where inventroy_operation.to_storage_id = storage.storage_id) st
        on op.to_storage_id = st.to_storage_id
               
        left join   (select  inventroy_operation.from_storage_id as from_storage_id,storage.name as name
        from  inventroy_operation , storage
        where inventroy_operation.from_storage_id = storage.storage_id) sm
        on op.from_storage_id = sm.from_storage_id
               
        left join   (select  inventroy_operation.to_store_id as to_store_id,store.name as name
        from  inventroy_operation , store
        where inventroy_operation.to_store_id = store.store_id) st1
        on op.to_store_id = st1.to_store_id
               
        left join   (select  inventroy_operation.from_store_id as from_store_id,store.name as name
        from  inventroy_operation , store
        where inventroy_operation.from_store_id = store.store_id) sm1
        on op.from_store_id = sm1.from_store_id
                   
        left join operation_reason re 
        on hi.operation_reason_id = re.operation_reason_id 
        WHERE 1=1
        <if test="operation_type_id != null and operation_type_id.length != 0">
            and
            <foreach collection="operation_type_id" item="operationTypeId" index="index"  open="(" separator="or" close=")">
                op.operation_type_id = #{operationTypeId} 
            </foreach>
        </if>
        <if test="storage_id != 0 and storage_id != null">
            and (op.from_storage_id = #{storage_id} or op.to_storage_id = #{storage_id})
        </if>        
        <if test="category_id != 0 and category_id != null">
            and pr.category_id like concat('%','(',#{category_id},')','%')
        </if>
        <if test="product_code != null">
            and pr.product_code like concat('%',#{product_code},'%')
        </if>
        <if test="product_name != null">
            and pr.name  like concat('%',#{product_name},'%')
        </if>
        and date(op.insert_time) between #{start_time} and #{end_time}
        group by hi.inventroy_history_id        
    </select>


注:and (op.operation_type_id = ? or op.operation_type_id = ?)spa

 

示例三:數組code

 public void testQuery() {
        ColInfoDao dao=(ColInfoDao)ctx.getBean("colInfoDao");
        Map map = new HashMap();
        map.put("userId", "tom");
        map.put("password", "123");
        String[] a = { "20000001", "20000002" };
        map.put("classIds", Arrays.asList(a));
        Object password = dao.query(map);
        System.out.println("password:" + password);
        Assert.assertEquals("123", password);
    }


XML:(感受不適合mybatis,可使用在ibatis中,iBatis 2.x 和 MyBatis 3.0.x)對象

<select id="queryPasswordByUserId" parameterClass="java.util.Map"      resultClass="java.lang.String">
        <![CDATA[
        select PASSWORD as password from T_S_P_USER
        ]]>
        <dynamic prepend="where">
            <isNotEmpty prepend="AND" property="userId">
                USER_ID=#userId#
            </isNotEmpty>
            <isNotEmpty prepend="AND" property="password">
                PASSWORD=#password#
            </isNotEmpty>
            <isNotEmpty prepend="AND" property="classIds">
                <iterate property="classIds" open="(" conjunction="OR" close=")">
                    CLASS_ID = #classIds[]#
                </iterate>
            </isNotEmpty>
        </dynamic>
</select>


示例四:Mapblog

map和List,array相比,map是用K,V存儲的,在foreach中,使用map時,index屬性值爲map中的Key的值。索引

由於map中的Key不一樣於list,array中的索引,因此會有更豐富的用法。ip

<insert id="ins_string_string">
        insert into string_string (key, value) values
        <foreach item="item" index="key" collection="map"
            open="" separator="," close="">(#{key}, #{item})</foreach>
</insert>

能夠看到這個例子至關簡單,表中須要兩個值,正好和K,V對應,於是map中的一個K,V就對應一條數據,若是map中有多個K,V,就會保存多個結果。

若是map中有兩對K,V,那麼執行SQL以下:

DEBUG [main] - ==>  Preparing: insert into string_string (key, value) values (?, ?) , (?, ?) 
DEBUG [main] - ==> Parameters: key 1(String), value 1(String), key 2(String), value 2(String)
DEBUG [main] - <==    Updates: 2

 

下面再看一個select的例子:

<select id="sel_key_cols" resultType="int">
        select count(*) from key_cols where
        <foreach item="item" index="key" collection="map"
            open="" separator="AND" close="">${key} = #{item}</foreach>
</select>

能夠看到這裏用key=value來做爲查詢條件,對於動態的查詢,這種處理方式能夠借鑑。必定要注意到$和#的區別,$的參數直接輸出,#的參數會被替換爲?,而後傳入參數值執行。

DEBUG [main] - ==>  Preparing: select count(*) from key_cols where col_a = ? AND col_b = ? 
DEBUG [main] - ==> Parameters: 22(Integer), 222(Integer)
DEBUG [main] - <==      Total: 1

最後,若是不考慮元素的順序和map中Key,map和list,array能夠擁有同樣的效果,都是存儲了多個值,而後循環讀取出來。

相關文章
相關標籤/搜索