<update id="updateUserBatch" parameterType="java.util.List">
<foreach collection="list" item="user" separator=";">
update sys_user
<set>
<if test="user.userCode != null and user.userCode != ''">
user_code = #{user.userCode},
</if>
</set>
where user_id = #{user.userId}
</foreach>
</update>
从上面的代码可以看出,这里使用了 <foreach collection="list" item="item" separator=";">...</foreach>
对传入的列表进行遍历更新。
其中,collection="list" 表示传入的参数是列表类型,item="user" 其中的 user 是自定义的名称(你也可以指定item="item" 这样的形式),表示单个更新的形参对象(Java 对象 User 有很多属性和表的字段对应),separator=";" 表示指定分隔符,对于批量更新操作而言分隔符参数必须是;,固定格式不能改变。如果是批量插入,分隔符参数则为, ,这也是固定的格式。
但是,在项目运行并执行更新用户操作代码时出现了异常,异常信息如下所示:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'update sys_user ...‘
在反复确认 SQL 语句没有写错的情况下,经过一番折腾才知道:如果使用 Mybatis 框架对 MySQL 数据库进行批量更新或者插入操作,需要在连接数据库的 URL 加上 allowMultiQueries=true
,这样便可以执行批处理操作了。
jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowMultiQueries=true
MySQL连接数据库时,添加语句:“allowMultiQueries=true”的作用:
1.可以在sql语句后携带分号,实现多语句执行。
2.可以执行批处理,同时发出多个SQL语句。