mybatis的批量insert和update

批量insert

<insert id="batchInsert" parameterType="java.util.List">
insert into 表名
(字段1,字段2,字段3……)
values
<foreach collection="list" item="item" index="index" separator=",">
  (#{item.字段1,jdbcType=类型},
  #{item.字段2,jdbcType=类型},
  #{item.字段3,jdbcType=类型}……
  )
</foreach>
</insert>

批量update

<foreach collection="list" item="item" index="index" open="" close="" separator=";">
  UPDATE 表名
  <set>
    <if test="item.字段1 != null">
      字段1 = #{item.字段1,jdbcType=类型},
    </if>
    <if test="item.字段2 != null">
      字段2 = #{item.字段2,jdbcType=类型},
    </if>
    <if test="item.字段3 != null">
      字段3 = #{item.字段3,jdbcType=类型},
    </if>
    ……
  </set>
  where 更新条件
</foreach>

这里有一点需要注意,当使用mysql的时候,有可能会保如下错:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

那是因为我们在设置数据库连接的时候没有指定可以批量更新的参数,在jdbc连接配置后面添加一下参数即可:

allowMultiQueries=true
发布了81 篇原创文章 · 获赞 16 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/mazhen1991/article/details/100235316