欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mybatis批量插入数据返回主键的实现

程序员文章站 2022-07-02 09:24:03
响应效果(id为主键): { "data": [ {"studentname": "张三","classno": "一班","id": 111},...

响应效果(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}
  ]
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。