1

我正在关注 SpringBoot + MyBatis 教程。我能够将简单的对象插入数据库。例如,我尝试插入一个员工对象:

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

我无法解决它,这不能像简单的员工示例中那样使用@Insert 来完成。请帮忙,因为我被困在这个问题上。

4

2 回答 2

1

如果您希望遍历 trough 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,因为我不知道你如何调用你的插入但替换你希望的方法

于 2021-06-23T08:27:49.767 回答
1

或者,您可以使用<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​​,建议使用批量插入

于 2021-06-23T10:33:08.653 回答