mybatis使用foreach进行批量插入和删除操作

时间:2022-01-08 08:57:52

一、批量插入

1.mapper层

 int insertBatchRoleUser(@Param("lists") List<RoleUser> lists);//@Param中的参数必须和mapper.xml中foreach的collection对应,若果不写@Param注解并且只传入一个list作为参数,则collection默认填list

2.mapper.xml

<insert id="insertBatchRoleUser">
INSERT INTO MS_USER_ROLE(ID, ROLEID, USERID,
STATUS, CREATETIME, UPDATETIME,
DELETETIME, CREATERID, UPDATERID,
DELETERID)
VALUES
<foreach collection="lists" item="user" separator=",">
(
#{user.id,jdbcType=VARCHAR}, #{user.roleid,jdbcType=VARCHAR}, #{user.userid,jdbcType=VARCHAR},
#{user.status,jdbcType=INTEGER}, #{user.createtime,jdbcType=TIMESTAMP}, #{user.updatetime,jdbcType=TIMESTAMP},
#{user.deletetime,jdbcType=TIMESTAMP}, #{user.createrid,jdbcType=VARCHAR}, #{user.updaterid,jdbcType=VARCHAR},
#{user.deleterid,jdbcType=VARCHAR}
)
</foreach>
</insert>

二、批量删除

1.mapper

int deleteBatchRoleUser(@Param("roleId") String roleId, @Param("list") List<String> userIds);

2.mapper.xml

<!-- 批量删除 -->
<delete id="deleteBatchRoleUser">
DELETE FROM MS_USER_ROLE WHERE ROLEID = #{roleId,jdbcType=VARCHAR} AND USERID IN
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id,jdbcType=VARCHAR}
</foreach>
</delete>