批量插入和获取生成的key时报错。 批量插入工作正常。
对象结构:
对象 1:
Long id, String name, Obj2 obj
对象 2:(Obj2)
Long id, String value
这两个对象存储在不同的表中。
表object1
id | name | object2_id (Foreign Key)
表object2
id | value
现在我有一个要插入的对象 1 列表。
该过程将插入 Object 2 获取 id,并插入 Object 1 以及 Object2的“id” strong>(作为外键)。
插入Object2时,Mapper.xml中的插入 block
案例 1:
<insert id="batchInsert" parameterType="list" useGeneratedKeys="true" keyProperty="obj1s.obj2.id">
<!-- obj1s is name of the list -->
insert into object2 (value) values
<foreach collection="obj1s" item="obj1" separator=",">
(#{obj1.obj2.id})
</foreach>
</insert>
ERROR: Error getting generated key or setting result to parameter object.
案例 2:
<insert id="batchInsert" parameterType="list" useGeneratedKeys="true" keyProperty="obj1.obj2.id">
<!-- obj1 so as to access the object of foreach loop -->
insert into object2 (value) values
<foreach collection="obj1s" item="obj1" separator=",">
(#{obj1.obj2.id})
</foreach>
</insert>
ERROR: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.binding.BindingException: Parameter 'obj1' not found. Available parameters are [obj1s, param1]
案例三:
<insert id="batchInsert" parameterType="list" useGeneratedKeys="true" keyProperty="obj2.id">
<!-- obj2 is the object with variable id to store generated key -->
insert into object2 (value) values
<foreach collection="obj1s" item="obj1" separator=",">
(#{obj1.obj2.id})
</foreach>
</insert>
ERROR: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.binding.BindingException: Parameter 'obj2' not found. Available parameters are [obj1s, param1]
有什么办法可以实现吗? 可能使用 selectKey,但 selectkey 用于不支持自动生成 key 的数据库。
使用 MyBatis 3.3.1 和 Mysql。
最佳答案
所以,我想通了。对于多行插入和使用生成的键,MyBatis 存在这个错误。 Bug 是列表变量名称必须是“列表” 进行批量插入和获取生成的 key 时。然后相应地访问对象。所以对于上面的示例,代码将如下所示:
<insert id="batchInsert" parameterType="list" useGeneratedKeys="true" keyProperty="obj2.id">
<!-- obj2 is the object with variable id to store generated key -->
insert into object2 (value) values
<foreach collection="list" item="obj1" separator=",">
(#{obj1.obj2.id})
</foreach>
mapper.java 方法声明如下所示:
public Integer batchInsert(@Param("list")List<Obj1> obj1);
变量名必须是list。没有别的。
感谢@blackwizard,我重新审视并检查了这个错误,这让我得到了这个答案。
关于mysql - MyBatis useGeneratedKeys 批量插入嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42160637/