距离上一次更新该文章已经过了 652 天,文章所描述的內容可能已经发生变化,请留意。
foreach元素的属性主要有
collection,item,index,open,separator,close。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| - collection: 要做foreach的对象,作为入参时,List对象默认用"list"代替作为键,数组对象"array"代替作为键,Map对象没有默认的键。 在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。 举个例子:如果User有属性List ids。入参是User对象,那么这个collection = "ids". 如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"
- item:集合中元素迭代时的别名,该参数为必选。
- index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
- open:foreach代码的开始符号,一般是(和close=")"合用。 常用在in(),values()时。该参数可选
- separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开, 避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
- close: foreach代码的关闭符号,一般是)和open="("合用。 常用在in(),values()时。该参数可选。
|
参数为map的例子
1 2 3 4 5 6 7 8 9
| -- mapper returnStock(@Param("prodCollect") Map<Long, Integer> prodCollect);
-- xml <update id="xxx"> <foreach collection="prodCollect" item="changeStocks" index="prodId" separator=";"> update xxx set total_stocks = total_stocks + #{changeStocks} where prod_id = #{prodId} </foreach> </update>
|
参数为list的例子(不写@param指定key的情况,则xml写collection="list",否则就是param的值,反之array也一样)
1 2 3 4 5 6 7 8 9 10
| -- maper insertBatch(List<xxx> orderItems);
-- xml <insert id="insertBatch"> INSERT INTO `xxx` (xxx) VALUES <foreach collection="list" item="orderItem" separator=","> (#{orderItem.xxx},#{orderItem.xxx}) </foreach> </insert>
|
mybatis之foreach用法