当批量插入并获取生成的密钥时,获取错误。
批量插入工作正常。
对象结构:
目标1:

Long id, String name, Obj2 obj

对象2:(Obj2)
Long id, String value

两个对象都存储在不同的表中。
表对象1
id | name  | object2_id (Foreign Key)

表对象2
id | value

现在我有一个对象1的列表要插入。
进程将是insert Object 2 get The id,insert Object 1 with“id”of Object2(作为外键)。
插入Object2时,Mapper.xml中的insert块
案例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>

错误:获取生成的密钥或将结果设置为参数对象时出错。
案例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>

错误:获取生成的密钥或将结果设置为参数对象时出错。原因:org.apache.ibatis.binding.BindingException:未找到参数“obj1”。可用参数为[obj1s,param1]
案例3:
<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>

错误:获取生成的密钥或将结果设置为参数对象时出错。原因:org.apache.ibatis.binding.BindingException:未找到参数“obj2”。可用参数为[obj1s,param1]
有什么办法可以达到这个目的吗?
可能使用selectKey,但selectKey用于不支持自动生成密钥的数据库。
使用MyBatis3.3.1和Mysql。

最佳答案

所以,我想出来了。MyBatis在多行插入和使用生成的密钥时存在此错误。错误在于在执行批插入和获取生成的密钥时,列表变量名必须是“list”。然后相应地访问对象。因此,对于上面的示例,代码将如下所示:

<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,我重新访问并检查了这个bug,这让我找到了这个答案。

关于mysql - MyBatis useGeneratedKeys用于批量插入中的嵌套对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42160637/

10-10 02:21