What is the implementation of Mybatis bulk insert data return primary key?
Today, I will talk to you about the implementation of Mybatis bulk insert data return primary key, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Response effect (id primary key):
{"data": [{"studentName": "Zhang San", "classNo": "Class 1", "id": 111}, {"studentName": "Li Si", "classNo": "Class 2", "id": 112}, {"studentName": "Wang Wu", "classNo": "Class one", "id": 113}]}}
Control layer:
@ PostMapping ("/ test") @ ResponseBody public Map test (@ RequestBody String data) {Map resultMap = new HashMap (); / / non-empty check if (! checkParams.checkString (data)) {resultMap.put ("code", "1"); resultMap.put ("msg", "parameter is empty.") ; return resultMap;} / / json to List JSONObject json= new JSONObject (data); String dataString = json.get ("data"). ToString (); com.google.gson.Gson gson = new Gson (); List list = gson.fromJson (dataString, new com.google.common.reflect.TypeToken () {}. GetType ()); / / request interface resultMap=registerService.test (list); return resultMap;}
Interface:
Public Map test (List data)
Implementation class:
@ Override public Map test (List data) {Map resultMap = new HashMap (); registerMapper.test (data); resultMap.put ("data", data); return resultMap;}
Persistence layer:
Public void test (List list)
Statement:
INSERT INTO student_info (student_name,class_no) VALUES (# {item.studentName}, # {item.classNo})
Request method:
Http://localhost/xxx/test
Request parameters:
{"data": [{"studentName": "Zhang San", "classNo": "Class one"}, {"studentName": "Li Si", "classNo": "Class two"}, {"studentName": "Wang Wu", "classNo": "Class one"]}}
Note:
The assignment of keyProperty in statement can be customized. If you change the value of keyProperty to key, change it to the following:
INSERT INTO student_info (student_name,class_no) VALUES (# {item.studentName}, # {item.classNo})
Then the response effect (key is the primary key) is as follows:
{"data": [{"studentName": "Zhang San", "classNo": "Class 1", "key": 111}, {"studentName": "Li Si", "classNo": "Class 2", "key": 112}, {"studentName": "Wang Wu", "classNo": "Class one", "key": 113}]}}
After reading the above, do you have any further understanding of the implementation of the Mybatis bulk insert data return primary key? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.