我们在进行数据插入时候,很多情况需要返回id,进而进行之后的处理,比如:传回前端之后进行更改,或者作为外键对其他表写入数据。

一般情况下都可以将需要插入表的内容提前处理到一个实体类中,但是可以偷懒直接传入在在xml中通过判断处理。下面记录几种插入数据返回id的情况(新标签中打开图片可以看得更清楚哦

1.  首先我们先创建一个测试使用的表。只是为了举常见的学生 - 成绩例子,正常情况,学生个人信息和成绩是要分开两张表的,多提一句现在已经很少使用建外键了。

SpringBoot+MyBatis插入数据返回id+内部类返回id+多参数

图1 学生表

2. 单个实体类插入数据返回id。--传入对象,在xml中指明自增和映射主键,,在执行完之后,在我们注入的那个类中直接取就可以取到id,这里是将整个对象返回到前端。

SpringBoot+MyBatis插入数据返回id+内部类返回id+多参数

图2 单个实体类接收返回id

  SpringBoot+MyBatis插入数据返回id+内部类返回id+多参数

  图3 测试接口和返回内容

附件:各个文件的源码:

 1 package com.example.demo.controller;
 2 
 3 import com.example.demo.domain.Result;
 4 import com.example.demo.entity.Student;
 5 import com.example.demo.service.StudentService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.web.bind.annotation.RequestBody;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RestController;
10 
11 import java.math.BigDecimal;
12 import java.util.Map;
13 
14 /**
15  * @author Codorld
16  * @date 2021/05/05 14:08
17  */
18 
19 @RestController
20 public class StudentController {
21 
22     @Autowired
23     StudentService studentService;
24 
25     // 将学生的的信息存入,并且将学生的id传回
26     @RequestMapping("inertStu")
27     public Result insertStudent(@RequestBody Map params) {
28         int yuwen_score = Integer.parseInt(params.get("yuwen_score").toString());
29         int shuxue_score = Integer.parseInt(params.get("shuxue_score").toString());
30         BigDecimal avg_score = BigDecimal.valueOf((double) (yuwen_score+shuxue_score)/2).setScale(2, BigDecimal.ROUND_HALF_UP);
31         Student student = new Student(params.get("stu_name").toString(), Integer.parseInt(params.get("stu_gender").toString()),
32                 yuwen_score, shuxue_score, avg_score);
33 
34         studentService.insertStudent(student);
35         return new Result("200", "插入学生信息成功", student);
36     }
37 }
StudentController

相关文章:

  • 2021-08-14
  • 2022-12-23
  • 2021-08-17
  • 2022-12-23
  • 2022-12-23
  • 2021-05-31
  • 2021-08-31
  • 2022-12-23
猜你喜欢
  • 2021-06-27
  • 2021-12-26
  • 2022-01-03
  • 2021-04-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案