controller:
@PostMapping public Result add(@RequestBody Emp emp){ log.info("添加员工:{}",emp); empService.add(emp); return Result.success(); }EmpExprMapper:
void insertBatch(List<EmpExpr> exprList);EmpMapper:
@Options(useGeneratedKeys = true, keyProperty = "id")//获取到生成的主键 -- 主键返回 @Insert("insert into emp(username, name, gender, phone, job, salary, image, entry_date, dept_id, create_time, update_time)\n" + " values (#{username},#{name},#{gender},#{phone},#{job},#{salary},#{image},#{entryDate},#{deptId},#{createTime},#{updateTime})") void insert(Emp emp);EmpServiceimp:
@Override public void add(Emp emp) { //1.设置默认时间和调用mapper emp.setCreateTime(LocalDateTime.now()); emp.setUpdateTime(LocalDateTime.now()); //2.保存员工基本信息 empMapper.insert(emp);//需要获得这个员工的id值传给exprList的empId,才能保存成功员工经历所属的员工 id //3.保存员工经历信息 - 批量保存 List<EmpExpr> exprList = emp.getExprList(); if(!CollectionUtils.isEmpty(exprList)){ //遍历集合,为empId赋值 exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId())); empExprMapper.insertBatch(exprList); }EmpExprMapper.xml:
<insert id="insertBatch"> insert into emp_expr(emp_id,begin,end,company,job) values <foreach collection="exprList" item="expr" separator=","> (#{expr.empId},#{expr.begin},#{expr.end},#{expr.company},#{expr.job}) </foreach> </insert>