mybatis提供了foreach
来循环集合进行操作,一般情况下,直接:
delete from t_document_user_group
where fgroupid = #{groupid}
and fuserid in
<foreach collection="userids" item="userid" separator="," open="(" close=")">
#{userid}
</foreach>
就能够实现循环list中的值。
在这里详细说一下foreach的属性:
- collection
是作为foreach循环的对象,入参是list<?>时要使用list作为键,数组对象作为入参时使用array作为键。
**可以在dao接口层使用@param("keyName")来设置键,设置后默认的键会失效,而采用keyName **
如果传入的对象存在list属性,则这个字段的名字作为键。 - item
作为循环体的具体对象 - separator
元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。 - open/close
open是foreach代码的开始符号,一般是“(”和close=")"合用。常用在in(),values()时。 - index
在list和数组中,index是元素的序号,在map中,index是元素的key。
今天写代码的时候,有一个插入操作,是一个list代表了用户id,其他值只是普通的属性,所以上面这种循环不太适用。
insert into t_document_user_group(fuserid, fgroupid, fcreator)
values
<foreach collection="userids" item="userid" separator=",">
(#{userid},#{groupid},#{creator})
</foreach>
这样就可以循环插入多个值。
如果批量插入时需要加上uuid作为唯一索引,通过mysql的函数uuid()是36位的,带4个-
横线,那么只需要在插入时写:
insert into t_document_permission (fvsign, fpermid)
values
<foreach collection="groupIds" item="groupid" separator=",">
(#{vsign},replace(uuid(),'-',''))
</foreach>
就可以生成32位,也可以upper(replace(uuid(),'-',''))
将uuid变成大写的字符串。
网友评论