Search code examples
javamybatis

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.


Solution

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

    i.e.

    <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.