[英]MyBatis, insert with complex object
I have the following scenario: 我有以下场景:
public class MyObj{
private String myField_1
private String myField_2
private MyChildObj myChild
// Constructor & get/set
}
public class MyChildObj{
private String myField_3
private String myField_4
// Constructor & get/set
}
on my Query.xml i wrote the insert in this way: 在我的Query.xml上,我用这种方式写了插入:
<insert id="insertMyObj" parameterType="MyObj">
INSERT INTO MY_TABLE ( FIELD_1,
FIELD_2,
FIELD_3,
FIELD_4)
values ( #{myField_1},
#{myField_2},
#{myField_3},
#{myField_4},
)
</insert>
after reading mybatis Result Map Guide i tried to add following lines on mybatis-config.xml file: 阅读mybatis结果地图指南后,我尝试在mybatis-config.xml文件中添加以下行:
<typeAliases>
<typeAlias alias="MyObj" type="myPackage.MyObj"/>
<typeAlias alias="MyChildObj" type="myPackage.MyChildObj"/>
</typeAliases>
<resultMap id="insertObj" type="MyObj">
<result property="myField_1" column="FIELD_1"/>
<result property="myField_2" column="FIELD_2"/>
<association property="PrimaryKeyMap" resultMap="PrimaryKey"/>
</resultMap>
<resultMap id="PrimaryKeyMap" type="PrimaryKey">
<result property=myField_3 column="FIELD_3"/>
<result property="myField_4" column="FIELD_4"/>
</resultMap>
but i keep getting the following error: 但我不断收到以下错误:
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: xx; columnNumber: xx; Element type "resultMap" must be declared.
Can anyone clarify me how to set up this? 谁能澄清我如何设置这个?
The resultMap
attribute in <association>
needs to refer to the name of your result map, not the Java type: <association property="MyChildObject" resultMap="PrimaryKeyMap"/>
<association>
的resultMap
属性需要引用结果映射的名称,而不是Java类型: <association property="MyChildObject" resultMap="PrimaryKeyMap"/>
However, if MyChildObject
is stored in the database as a separate table, nested inserts are not supported . 但是,如果MyChildObject
作为单独的表存储在数据库中, 则不支持嵌套插入。 You will need to call both inserts in Java. 您需要在Java中调用两个插入。 ResultMaps are for selects . ResultMaps用于选择 。
If you are just putting a few columns from one table in a separate object, then you can do this with dot notation, myChildObject.myField_4
. 如果您只是将一个表中的几列放在单独的对象中,那么可以使用点表示法myChildObject.myField_4
来执行此myChildObject.myField_4
。 Something like this: 像这样的东西:
<insert id="insertMyObj" parameterType="MyObj">
INSERT INTO MY_TABLE ( FIELD_1,
FIELD_2,
FIELD_3,
FIELD_4)
values ( #{myField_1},
#{myField_2},
#{myChildObject.myField_3},
#{myChildObject.myField_4},
)
</insert>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.