【问题标题】:Mybatis Use generated keys for Batch InsertMybatis 使用生成的密钥进行批量插入
【发布时间】:2013-09-05 03:45:52
【问题描述】:

我已经在 Mybatis 中完成了批量插入,并且工作正常。但我不确定如何存储 bean 类中每一行生成的主键。这是我的代码,

映射器.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;
}
}

在上面的例子中,Employee是要保存在数据库中的对象,其中包含Emp列表。

【问题讨论】:

    标签: java mybatis


    【解决方案1】:

    但我不确定如何存储每行生成的主键 在 bean 类中。

    如果你想用你的 pojo 映射生成的主键,那么插入 xml 中的 foreach 将不起作用。您必须使用 useGeneratedKeys="true" 编写简单的插入,并为要保留的每条记录调用它。

    我已经给出详细解答here

    【讨论】:

      【解决方案2】:

      尝试在插入块中使用useGeneratedKeys="true" keyProperty="id" keyColumn="id"

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

      为什么使用select 做内部插入?只是想知道。

      【讨论】:

      • 不需要写keyProperty="id",因为它是该选项的默认值。
      • 我按你说的试过了,但得到错误stackoverflow.com/questions/28453475/…你能帮忙吗?
      • @iJava:当然可以,但可能需要一些时间。希望你不着急
      • @indyaah 谢谢你的回答。我仍然无法解决这个问题。所以我在等....
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 2013-03-19
      相关资源
      最近更新 更多