我試圖做一個插入語句,將允許我插入到一個塊中的多個表,但沒有任何成功。這裏有一個例子:MyBatis複雜插入
Java對象:
public class Parent {
String parentId;
List<Child> children;
...getters and setters...
}
public class Child {
String childId;
List<Toy> toys;
...getters and setters...
}
public class Toy {
String toyId;
String color;
...getters and setters...
}
MySQL表
create table TOY (TOY_ID varchar(10), COLOR varchar(10), CHILD_ID varchar(10),
primary key(TOY_ID), foreign key (CHILD_ID) references CHILD(CHILD_ID));
create table CHILD (CHILD_ID varchar(10), PARENT_ID varchar(10),
primary key(CHILD_ID), foreign key (PARENT_ID) references PARENT(PARENT_ID));
create table PARENT (PARENT_ID varchar(10), primary key(PARENT_ID));
mapper.xml
<resultMap id="ToyResult" type="Toy">
<id property="toyId" column="TOY_ID"/>
<result property="color" column="COLOR"/>
</resultMap>
<resultMap id="ChildResult" type="Child">
<id property="childId" column="CHILD_ID"/>
<collection property="toys" ofType="Toy" resultMap="ToyResult"/>
</resultMap>
<resultMap id="ParentResult" type="Parent">
<id property="parentId" column="PARENT_ID"/>
<collection property="children" ofType="Child" resultMap="childResult"/>
</resultMap>
我想知道,如果它是可以做到的插入映射如下:
<insert id="insertParentData" parameterType="Parent">
insert into PARENT(PARENT_ID) values(#{parentId});
insert into CHILD(CHILD_ID, PARENT_ID) values
<foreach collection="children" item="childItem" index="index0" separator=",">
(#{childItem.childId}, #{parentId})
</foreach>;
insert into TOY(TOY_ID, COLOR, CHILD_ID) values
<foreach collection="children" item="childItem" index="index0" separator=",">
<foreach collection="childItem.toys" item="toyItem" index="index1" separator=",">
(#{toyItem.toyId}, #{toyItem.color}, #{childItem.childId})
</foreach>
</foreach>
</insert>
我一直在收到一條錯誤消息,說我的SQL語法有錯誤。它指出insert into CHILD
系列。
如果這種插入方法是不可能的,你會如何建議我映射插入語句?我可以創建ParentMapper,ChildMapper和ToyMapper xml文件,並且在我的父數據訪問對象中,我將有三次插入調用,每次都使用不同的映射器插入到不同的表中。
感謝您的幫助。
可能重複:https://stackoverflow.com/questions/31649089/mybatis-insert-with-complex-object 也有關:https://stackoverflow.com/questions/4287544/persist-collection-in-object -with-mybatis –
@GabrielMolina謝謝你,我以前沒見過這個問題。我決定分開插入並分別調用每一個。 – George
個人插入是要走的路。只需將所有插入操作包裝在事務中,以便在出現故障時全部回滾。 – DwB