简体   繁体   中英

Mybatis Use generated keys for Batch Insert

I have done batch inserting in Mybatis and it is working fine. But I'm not sure how to store the generated primary keys for each row in the bean class. Here is my code,

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

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

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.

Try using useGeneratedKeys="true" keyProperty="id" keyColumn="id" with your insert block.

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? Just wondering.

But I'm not sure how to store the generated primary keys for each row in the bean class.

If you want to map the generated primary key with your pojo then foreach inside the insert xml won't work. You'll have to write simple insert with useGeneratedKeys="true" and call it for each record that you want to persist.

I have given detailed answer here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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