SpringBoot+MyBatis插入數據返回id+內部類返回id+多參數


我們在進行數據插入時候,很多情況需要返回id,進而進行之后的處理,比如:傳回前端之后進行更改,或者作為外鍵對其他表寫入數據。

一般情況下都可以將需要插入表的內容提前處理到一個實體類中,但是可以偷懶直接傳入在在xml中通過判斷處理。下面記錄幾種插入數據返回id的情況(新標簽中打開圖片可以看得更清楚哦

1.  首先我們先創建一個測試使用的表。只是為了舉常見的學生 - 成績例子,正常情況,學生個人信息和成績是要分開兩張表的,多提一句現在已經很少使用建外鍵了。

圖1 學生表

2. 單個實體類插入數據返回id。--傳入對象,在xml中指明自增和映射主鍵,,在執行完之后,在我們注入的那個類中直接取就可以取到id,這里是將整個對象返回到前端。

圖2 單個實體類接收返回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
 1 package com.example.demo.entity;
 2 
 3 import lombok.AllArgsConstructor;
 4 import lombok.Data;
 5 import lombok.NoArgsConstructor;
 6 
 7 import java.math.BigDecimal;
 8 
 9 /**
10  * @author Codorld
11  * @date 2021/05/05 14:01
12  */
13 
14 @NoArgsConstructor
15 @AllArgsConstructor
16 @Data
17 public class Student {
18 
19     // 學生id - 學號
20     private int stu_id;
21 
22     // 學生姓名
23     private String stu_name;
24 
25     // 學生性別 1.男 2.女
26     private int stu_gender;
27 
28     // 語文成績
29     private int yuwen_socre;
30 
31     // 數學成績
32     private int shuxue_socre;
33 
34     // 平均分(保留小數點兩位)
35     private BigDecimal avg_score;
36 
37     // 只姓名、性別、語文、數學和平均成績的構造方法
38     public Student(String stu_name, int stu_gender, int yuwen_socre, int shuxue_socre, BigDecimal avg_score) {
39         this.stu_name = stu_name;
40         this.stu_gender = stu_gender;
41         this.yuwen_socre = yuwen_socre;
42         this.shuxue_socre = shuxue_socre;
43         this.avg_score = avg_score;
44     }
45 
46 }
Student.java
 1 package com.example.demo.mapper;
 2 
 3 import com.example.demo.entity.Student;
 4 import org.apache.ibatis.annotations.Mapper;
 5 
 6 /**
 7  * @author Codorld
 8  * @date 2021/05/05 14:18
 9  */
10 
11 @Mapper
12 public interface StudentMapper {
13 
14     // 插入一條學生數據返回學生id
15     void insertStudent(Student student);
16 
17 }
StudentMapper.java
 1 package com.example.demo.service;
 2 
 3 import com.example.demo.entity.Student;
 4 
 5 /**
 6  * @author Codorld
 7  * @date 2021/05/05 14:11
 8  */
 9 
10 public interface StudentService {
11 
12     // 插入學生數據返回id
13     void insertStudent(Student student);
14 
15 }
StudentService.java
 1 package com.example.demo.service.impl;
 2 
 3 import com.example.demo.entity.Student;
 4 import com.example.demo.mapper.StudentMapper;
 5 import com.example.demo.service.StudentService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 
 9 /**
10  * @author Codorld
11  * @date 2021/05/05 14:13
12  */
13 
14 @Service("studentService")
15 public class StudentServiceImpl implements StudentService {
16 
17     @Autowired
18     StudentMapper studentMapper;
19 
20     @Override
21     public void insertStudent(Student student) {
22         studentMapper.insertStudent(student);
23     }
24 }
StudentServiceImpl.java
StudentMapper.xml
 1 package com.example.demo;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 
 7 @SpringBootApplication
 8 @MapperScan("com.example.demo.mapper")
 9 public class DemoApplication {
10     public static void main(String[] args) {
11         SpringApplication.run(DemoApplication.class, args);
12 
13     }
14 
15 }
DemoApplication.java
 1 # Web Server 配置
 2 server:
 3   port: 9091
 4   servlet:
 5     context-path: /demoBlog
 6     session:
 7       timeout: 60m
 8 
 9 # MyBatis配置
10 Spring:
11   datasource:
12     url: jdbc:mysql://localhost:3306/demoblog?allowMultiQueries=true
13     username: root
14     password: 123456
15     driver-class-name: com.mysql.cj.jdbc.Driver
16 
17 mybatis:
18   #mapper
19   mapper-locations: classpath:mapper/*.xml
20   type-aliases-package: com.example.demo.entity
21 
22 #sql - 打印sql語句,推薦安裝一個插件:mybatis log
23 logging:
24   level:
25     com:
26       example:
27         demo:
28           mapper: debug
application.yaml
 1 package com.example.demo.domain;
 2 
 3 import lombok.AllArgsConstructor;
 4 import lombok.Data;
 5 import lombok.NoArgsConstructor;
 6 
 7 /**
 8  * @author Codorld
 9  * @date 2021/05/05 14:15
10  */
11 
12 @AllArgsConstructor
13 @NoArgsConstructor
14 @Data
15 public class Result {
16     private String code;
17     private String msg;
18     private Object data;
19 
20     public Result(String code, String msg) {
21         this.code = code;
22         this.msg = msg;
23     }
24 }
Result.java

 

3. 多參數情況:只是在xml中取值有一點不同,同時不指定參數類型即可。

  對上面內容進行修改:

  ①mapper和service中加入平均值的參數

  ②student中添加出去平均值的構造函數

  ③在controller中構建student時候使用②中的構造函數

  ④xml中使用多參數取值方法,即使用#{student.x}取值,其他參數還是直接使用#{avg_score}

圖4 多參數返回id時候的情況

圖5 測試結果

  注:從返回結果中可以看到只會映射id,不是表中所有內容都映射到類中。

 附件:

 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);
33 
34         studentService.insertStudent(student, avg_score);
35         return new Result("200", "插入學生信息成功", student);
36     }
37 }
StudentController.java
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <!--@author Codorld-->
 4 <!--投標結果的讀取的xml-->
 5 <mapper namespace="com.example.demo.mapper.StudentMapper">
 6 
 7     <!--同學對象注入的方式來獲取插入學生自長的id-->
 8     <insert id="insertStudent" keyProperty="student.stu_id" useGeneratedKeys="true">
 9 
10         insert into student(stu_name, stu_gender, yuwen_score, shuxue_socre, avg_score)
11         values (#{student.stu_name}, #{student.stu_gender}, #{student.yuwen_socre}, #{student.shuxue_socre},
12                 #{avg_score});
13 
14     </insert>
15 
16 </mapper>
StudentMapper.xml

 

4. 內部類返回id + 多參數:此中情況只需要新建一個內部類,改變controller中需要導入的對象,和mapper與service中的參數類型,xml中不改變具體看代碼,測試結果與上圖相同。

 1 package com.example.demo.controller;
 2 
 3 import com.example.demo.domain.Result;
 4 import com.example.demo.entity.OutStudent;
 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 
32         OutStudent.Student student = new OutStudent.Student();
33 
34         student.setStu_name(params.get("stu_name").toString());
35         student.setStu_gender(Integer.parseInt(params.get("stu_gender").toString()));
36         student.setYuwen_socre(yuwen_score);
37         student.setShuxue_socre(shuxue_score);
38         //student.setAvg_score(avg_score);
39 
40         studentService.insertStudent(student, avg_score);
41         return new Result("200", "插入學生信息成功", student);
42     }
43 }
StudentController.java
 1 package com.example.demo.entity;
 2 
 3 import lombok.Data;
 4 
 5 import java.math.BigDecimal;
 6 
 7 /**
 8  * @author wangXiaoMing
 9  * @date 2021/05/05 17:51
10  */
11 
12 @Data
13 public class OutStudent {
14 
15     private int any_one;
16 
17     private Student student;
18 
19     // 執行人(小組成員)
20     @Data
21     public static class Student {
22 
23         // 學生id - 學號
24         private int stu_id;
25 
26         // 學生姓名
27         private String stu_name;
28 
29         // 學生性別 1.男 2.女
30         private int stu_gender;
31 
32         // 語文成績
33         private int yuwen_socre;
34 
35         // 數學成績
36         private int shuxue_socre;
37 
38         // 平均分(保留小數點兩位)
39         private BigDecimal avg_score;
40 
41     }
42 }
OutStudent.java

以下修改參數類型:

 1 package com.example.demo.service;
 2 
 3 import com.example.demo.entity.OutStudent;
 4 
 5 import java.math.BigDecimal;
 6 
 7 /**
 8  * @author Codorld
 9  * @date 2021/05/05 14:11
10  */
11 
12 public interface StudentService {
13 
14     // 插入學生數據返回id
15     void insertStudent(OutStudent.Student student, BigDecimal avg_score);
16 
17 }
StudentService.java
 1 package com.example.demo.service.impl;
 2 
 3 import com.example.demo.entity.OutStudent;
 4 import com.example.demo.mapper.StudentMapper;
 5 import com.example.demo.service.StudentService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 
 9 import java.math.BigDecimal;
10 
11 /**
12  * @author Codorld
13  * @date 2021/05/05 14:13
14  */
15 
16 @Service("studentService")
17 public class StudentServiceImpl implements StudentService {
18 
19     @Autowired
20     StudentMapper studentMapper;
21 
22     @Override
23     public void insertStudent(OutStudent.Student student, BigDecimal avg_score) {
24         studentMapper.insertStudent(student, avg_score);
25     }
26 }
StudentServiceImpl.java
 1 package com.example.demo.mapper;
 2 
 3 import com.example.demo.entity.OutStudent;
 4 import org.apache.ibatis.annotations.Mapper;
 5 
 6 import java.math.BigDecimal;
 7 
 8 /**
 9  * @author Codorld
10  * @date 2021/05/05 14:18
11  */
12 
13 @Mapper
14 public interface StudentMapper {
15 
16     // 插入一條學生數據返回學生id
17     void insertStudent(OutStudent.Student student, BigDecimal avg_score);
18 
19 }
StudentMapper.java

以下未改變:

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <!--@author Codorld-->
 4 <!--投標結果的讀取的xml-->
 5 <mapper namespace="com.example.demo.mapper.StudentMapper">
 6 
 7     <!--同學對象注入的方式來獲取插入學生自長的id-->
 8     <insert id="insertStudent" keyProperty="student.stu_id" useGeneratedKeys="true">
 9 
10         insert into student(stu_name, stu_gender, yuwen_score, shuxue_socre, avg_score)
11         values (#{student.stu_name}, #{student.stu_gender}, #{student.yuwen_socre}, #{student.shuxue_socre},
12                 #{avg_score});
13 
14     </insert>
15 
16 </mapper>
StudentMapper.xml

 

  思考:那么什么情況才使用得到內部類這種東西,其實原理跟多參數一樣的,只是當我們創建類時候不可能每張表都要去創建一個員工表,比如我們可以通過創建一個整體的類,但是又需要添加數據時候那個id,我們就可以使用內部類的情況,一般在list一些數據時候都需要傳給前端id以便之后的處理,所以這個內部類不僅僅可以在插入時候返回id使用,也可以作為結果集使用。對於內部類在結果集的使用在,另外一篇博客      巴拉巴拉巴拉   今天沒時間了,之后寫上補上超鏈接。

 

記得把總的鏈接也補上。

 

 

 

標題:微軟雅黑

內容:楷體

斜體:仿宋

 

 

貼代碼時候添加了行號,會不方便復制,但是內容不是很難,還是簡易手敲一遍。


對待代碼的態度,會影響到自己。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM