spring boot + mybatis实现批量插入数据
场景描述:前端以List的形式传入多条待插入数据,调用mybatis-generator自动生成的insert接口一次只能插入一条数据,当然可以写一个for循环一条条插入,但感觉效率太低;所以尝试下一条sql插入多条数据;
解决方案:使用foreach方法来实现多条记录的批量插入
实现方式如下:
controller
@ApiOperation(value = "新增多个部门") @PostMapping("insertDepartments") public ResultMsg newDepartment(@RequestBody List<Department > departments ) { int result = departmentService.insertDepts(departments); return ResultMsg.getStrMsg(result > 0 ? "SUCCESS" : "FAILED"); }
service
public int insertDepts(List<Department > departments) { try{ return departmentMapper.insertDepartments(departments); }catch (Exception e ) { logger.info(e.toString()); return -1; } }
mapper
int insertDepartments(List<Department> list);
xml
<insert id="insertDepartments" useGeneratedKeys="true" keyProperty="id" parameterType="com.wg.demo.po.Department"> insert into department (id, dept_name, descr, create_time) values <foreach collection="list" item="dept" index="index" separator=","> (#{dept.id,jdbcType=BIGINT}, #{dept.deptName,jdbcType=VARCHAR}, #{dept.descr,jdbcType=VARCHAR}, #{dept.createTime,jdbcType=TIMESTAMP}) </foreach> </insert>
测试: