批量插入並獲取生成的密鑰時,出現錯誤。 批量插入工作正常。MyBatis useGeneratedKeys用於批量插入中的嵌套對象
對象結構:
對象1:
Long id, String name, Obj2 obj
對象2:(OBJ2)
Long id, String value
這兩個對象被存儲在不同的表中。
表object1
id | name | object2_id (Foreign Key)
表對象2
id | value
現在我有對象1列表插入。
的過程中會插入對象2獲得ID,並插入對象1與對象2 「ID」(如外鍵)。
雖然插入Object2的,在Mapper.xml
插塊情況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]
案例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>
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用於不支持自動生成密鑰的DB。
使用MyBatis 3.3.1和Mysql。
請澄清映射類/屬性<=>表/列 – blackwizard
@blackwizard映射可以通過列名和屬性名稱計算出來。 – Shuddh