简体   繁体   English

Mybatis使用生成的键进行批量插入

[英]Mybatis Use generated keys for Batch Insert

I have done batch inserting in Mybatis and it is working fine. 我在Mybatis中完成了批量插入,它运行正常。 But I'm not sure how to store the generated primary keys for each row in the bean class. 但是我不确定如何为bean类中的每一行存储生成的主键。 Here is my code, 这是我的代码,

Mapper.xml Mapper.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.xxxx.sample.test.dao.TestDAO">
        <insert id="insertEmployeeList" parameterType="java.util.List">
            INSERT ALL
            <foreach collection="list" item="element" index="index">
                INTO EMPLOYEE (name) values (#{element.name})
            </foreach>
            SELECT * FROM dual
        </insert>
    </mapper>

Emp.java Emp.java

public class Emp {
public Emp(int id, String name) {
this.id = id;
this.name = name;
}
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Employee.java Employee.java

public class Employee {
private List<Emp> list = new ArrayList<Emp>();
public List<Emp> getList() {
return list;
}
public void setList(List<Emp> list) {
this.list = list;
}
}

In the above example Employee is the object to be persisted in database which contains list of Emp. 在上面的示例中,Employee是要保存在包含Emp列表的数据库中的对象。

Try using useGeneratedKeys="true" keyProperty="id" keyColumn="id" with your insert block. 尝试使用useGeneratedKeys="true" keyProperty="id" keyColumn="id"和您的插入块。

ie

<insert id="insertEmployeeList" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id"  keyColumn="id">
INSERT ALL
  <foreach collection="list" item="element" index="index">
    INTO EMPLOYEE (name) values (#{element.name})
  </foreach>
</insert>

Why use select doing inside insert? 为什么select在插入内部做? Just wondering. 就是想。

But I'm not sure how to store the generated primary keys for each row in the bean class. 但是我不确定如何为bean类中的每一行存储生成的主键。

If you want to map the generated primary key with your pojo then foreach inside the insert xml won't work. 如果要将生成的主键映射到pojo,则insert xml中的foreach将不起作用。 You'll have to write simple insert with useGeneratedKeys="true" and call it for each record that you want to persist. 您必须使用useGeneratedKeys =“true”编写简单插入,并为要保留的每条记录调用它。

I have given detailed answer here 在这里给出了详细的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM