在 MyBatis 中對 Oracle(或其他數據庫)進行批量插入,核心是使用 `
<mapper namespace="com.example.dao.UserMapper">
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO t_user (id, username, email, create_time)
VALUES
<foreach collection="list" item="user" separator=",">
(#{user.id}, #{user.username}, #{user.email}, #{user.createTime})
</foreach>
</insert>
</mapper>
| 屬性 | 說明 | 本例值 |
|---|---|---|
| collection | 要遍歷的集合參數名。若參數是 List,默認名為 `list`;若是 Map,需指定 key。 | `list` |
| item | 遍歷出的單個元素別名,用於 `#{item.property}` 訪問屬性。 | `user` |
| separator | 元素之間的分隔符,批量插入必須為逗號 `,`。 | `,` |
| open / close | (可選)整個遍歷結果的前後綴,如 `(` 和 `)`。此處直接放在 `VALUES` 後不需要。 | — |
Oracle 不支持標準 `VALUES (...), (...)` 多行插入語法(12c 前)。需改用 `INSERT ALL ... SELECT * FROM DUAL`:
<insert id="batchInsertOracle" parameterType="java.util.List">
INSERT ALL
<foreach collection="list" item="user">
INTO t_user (id, username, email, create_time)
VALUES (#{user.id}, #{user.username}, #{user.email}, #{user.createTime})
</foreach>
SELECT * FROM DUAL
</insert>
或使用 `UNION ALL` 子查詢(性能略差)。
// Mapper 接口
void batchInsert(@Param("list") List userList);
// Service 調用
List users = buildUsers(1000);
userMapper.batchInsert(users);
掌握 `