批量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
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐