前端傳遞多筆資料 (如表單動態新增多列),後端需批次寫入資料庫。MyBatis Mapper 定義:
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO user_role (user_id, role_id) VALUES
<foreach collection="list" item="item" separator=",">
(#{item.userId}, #{item.roleId})
</foreach>
</insert>
@PostMapping("/batchSave")
public Result batchSave(@RequestBody List dtos) {
List entities = new ArrayList<>();
for (UserRoleDTO dto : dtos) {
UserRole entity = new UserRole();
entity.setUserId(dto.getUserId());
entity.setRoleId(dto.getRoleId());
// 其他欄位映射...
entities.add(entity);
}
userRoleService.batchInsert(entities);
return Result.success();
}
// Service
public void batchInsert(List list) {
if (list == null || list.isEmpty()) return;
mapper.batchInsert(list); // MyBatis 自動處理 foreach
}
// Mapper Interface
void batchInsert(List list);
[
{ "userId": 101, "roleId": 1 },
{ "userId": 101, "roleId": 3 },
{ "userId": 102, "roleId": 2 }
]
max_allowed_packet (MySQL) 或導致解析緩慢。建議 **500-1000 筆分批**。SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
try {
UserRoleMapper mapper = sqlSession.getMapper(UserRoleMapper.class);
for (UserRole entity : entities) {
mapper.insert(entity); // 單條 insert,但批次提交
}
sqlSession.commit();
} finally {
sqlSession.close();
}
LOAD DATA INFILE (MySQL) / COPY (PostgreSQL) 超大量匯入。application/x-www-form-urlencoded 陣列格式,後端用 @RequestParam List 接收失敗 → 改用 @RequestBody 接收 JSON 陣列。<foreach> 指定 collection="list" (參數為 List 時預設即為 list,但明確指定較保險)。正確封裝 List<Entity>> 並搭配 MyBatis <foreach>,即可高效完成批次新增。