這篇文章將為大家詳細講解有關使用Mybatis怎么批量插入數據并返回主鍵,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
響應效果(id為主鍵):
{
"data": [
{"studentName": "張三","classNo": "一班","id": 111},
{"studentName": "李四","classNo": "二班","id": 112},
{"studentName": "王五","classNo": "一班","id": 113}
]
}控制層:
@PostMapping("/test")
@ResponseBody
public Map<String, Object> test(@RequestBody String data) {
Map<String, Object> resultMap = new HashMap<String, Object>();
//非空校驗
if (!checkParams.checkString(data)) {
resultMap.put("code", "1");
resultMap.put("msg", "參數為空。");
return resultMap;
}
//json轉List<Map<String, Object>>
JSONObject json= new JSONObject(data);
String dataString = json.get("data").toString();
com.google.gson.Gson gson = new Gson();
List<Map<String, Object>> list = gson.fromJson(dataString, new com.google.common.reflect.TypeToken<List<Map<String, Object>>>() {
}.getType());
//請求接口
resultMap=registerService.test(list);
return resultMap;
}接口:
public Map<String, Object> test(List<Map<String,Object>> data);
實現類:
@Override
public Map<String, Object> test(List<Map<String,Object>> data) {
Map<String, Object> resultMap = new HashMap<String, Object>();
registerMapper.test( data);
resultMap.put("data",data);
return resultMap;
}持久層:
public void test(List<Map<String,Object>> list);
statement:
<!-- =========================批量插入返回主鍵示例======================== -->
<insert id="test" parameterType="list" useGeneratedKeys="true" keyProperty="id" >
INSERT INTO student_info(student_name,class_no)VALUES
<foreach collection="list" item="item" separator=",">
(
#{item.studentName},
#{item.classNo}
)
</foreach>
</insert>請求方式:
http://localhost/xxx/test
請求參數:
{
"data": [
{"studentName": "張三","classNo": "一班"},
{"studentName": "李四","classNo": "二班"},
{"studentName": "王五","classNo": "一班"}
]
}注意事項:
statement中keyProperty的賦值是可以自定義的,如果將keyProperty的值改為key,即改成如下:
<!-- =========================批量插入返回主鍵示例======================== -->
<insert id="test" parameterType="list" useGeneratedKeys="true" keyProperty="key" >
INSERT INTO student_info(student_name,class_no)VALUES
<foreach collection="list" item="item" separator=",">
(
#{item.studentName},
#{item.classNo}
)
</foreach>
</insert>則響應效果(key為主鍵)如下:
{
"data": [
{"studentName": "張三","classNo": "一班","key": 111},
{"studentName": "李四","classNo": "二班","key": 112},
{"studentName": "王五","classNo": "一班","key": 113}
]
}關于使用Mybatis怎么批量插入數據并返回主鍵就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。