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

一、批量插入

1.mapper层

 int insertBatchRoleUser(@Param("lists") List 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 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>

 

转载于:https://www.cnblogs.com/Amaris-Lin/p/8615977.html

你可能感兴趣的:(mybatis使用foreach进行批量插入和删除操作)