foreach批量插入数据库

发布时间 2023-09-22 23:34:44作者: 高桥芒果

批量插入数据库

错误报告如下

Cause: 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 'insert into t_checkgroup_checkitem
        (checkitem_id,checkgroup_id)
' at line 5
; bad SQL grammar []; nested exception is 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 'insert into t_checkgroup_checkitem
(checkitem_id,checkgroup_id)
' at line 5
at com.heima.service.impl.CheckGroupServiceImplTest.addTest(CheckGroupServiceImplTest.java:26)
Caused by: 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 'insert into t_checkgroup_checkitem
(checkitem_id,checkgroup_id)
' at line 5
at com.heima.service.impl.CheckGroupServiceImplTest.addTest(CheckGroupServiceImplTest.java:26)

这个错误是由于在 <foreach>​ 标签中使用了 insert​ 语句,导致了 SQL 语法错误。在 MySQL 中,不能在一条 SQL 语句中执行多次 insert​ 操作。执行的错误SQL语句如下:

可以将 insert​ 语句移出 <foreach>​ 标签,然后在 <foreach>​ 标签中构造多个 values​ 子句,如下所示:

<insert id="add" parameterType="java.util.Map">
    insert into t_checkgroup_checkitem
    (checkgroup_id, checkitem_id)
    <foreach collection="checkitemIds" item="id" separator=",">
        values  (#{checkGroupId}, #{id})
    </foreach>
</insert>

然而,上面的代码还是不能正常工作,执行的错误SQL语句如下:

要把Value拿到的前面

而且因为 MySQL 不允许在一条 insert​ 语句中插入多组数据时,各组数据之间用逗号分隔。所以,需要修改 separator​ 属性的值,将其设置为 ","​如下所示:

<insert id="add" parameterType="java.util.Map">
    insert into t_checkgroup_checkitem
    (checkgroup_id, checkitem_id)
    values
    <foreach collection="checkitemIds" item="id" separator="),(">
        (#{checkGroupId}, #{id})
    </foreach>
</insert>

这样,生成的 SQL 语句应该类似于以下形式,这是符合 MySQL 语法的:

SQL复制insert into t_checkgroup_checkitem
(checkgroup_id, checkitem_id)
values 
(value1, value2),
(value3, value4),
...