如何使用 mybatis 在数据库中插入 java HashMap 键和值作为列

How to insert java HashMap keys and values as columns in database using mybatis

我正在使用 SpringBoot + MyBatis tutorial.I 我能够将简单的对象插入到数据库中。例如,我尝试插入一个员工对象:

Employee{
    private String id;
    private String name;
}


@Mapper
public interface EmployeeMapper {  

    @Insert("insert into employee(id,name) values(#{id},#{name})")
    void insert(Employee employee);
 }

现在我想插入另一个对象,如下所示:

Department{
    // deptId will be common for all employees in the map
    private int deptId;

    //employeeMap is a Map employees where employeeId is key and employeeName is value
    private Map<String, String> employeeMap;
  }

 //Eg. I have the following data in Department Object
 Department dept = new Department();
 dept.setId("d1");

 Map<String, String> employeeMap = new HashMap<String, String>();
 employeeMap.put("1","Jon");
 employeeMap.put("2","Doe");
 employeeMap.put("3","Sam");
 dept.setEmployeeMap(employeeMap);

 // I want to insert dept object as 3 columns in database
 //*deptId* will be common for all employees in Map
 //*employeeId* key of map 
 //*employeeName* valiue of map

我无法解决它,难道不能像简单的 Employee 示例中那样使用 @Insert 来完成吗?请帮忙,因为我被困在这。

如果您希望遍历 map 并获取每个键和该键的值,最简单的方法是

Iterator hmIterator = employeeMap.entrySet().iterator();
while (hmIterator.hasNext()){
    Map.Entry mapElement = (Map.Entry)hmIterator.next();
    String name = (String)mapElement.GetValue();
    String number = (String)mapElement.getKey();
    insert(number,name);
}

或者没有迭代器

for (Map.Entry<String,String> entry : map.entrySet()){
    String key = entry.getKey(); //this is your number
    String value = entry.getValue(); //this is your name
    insert(key,value);
}

或者另一种方法是

for (String key : employeeMap.keySet()){
    String name = employeeMap.get(key);
    insert(key, name);
}

注意:我只写了函数 insert,因为我不知道你如何调用你的插入,但可以用你希望的方法替换它

或者,您可以使用 <foreach /> 迭代映射条目。
'key'赋值给index指定的变量,'value'赋值给item指定的变量。

因为你没有给我看 SQL,我假设你的数据库支持 multi-row insert

@Insert({ "<script>",
  "insert into employee (deptId, employeeId, employeeName) values",
  "<foreach collection='employeeMap' index='key' item='value'",
      "separator=','>",
    "(#{deptId}, #{key}, #{value})",
  "</foreach>",
  "</script>"
})
void insert(Department dept);

然后 MyBatis 会准备如下语句。

insert into employee (deptId, employeeId, employeeName) 
  values (?, ?, ?) , (?, ?, ?) , (?, ?, ?)

请注意,当employeeMap中有很多条目时,建议使用batch insertion