MyBatis, insert with complex object

Koop4 picture Koop4 · Jul 27, 2015 · Viewed 16.6k times · Source

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:

<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:

<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?

Answer

AngerClown picture AngerClown · Jul 27, 2015

The resultMap attribute in <association> needs to refer to the name of your result map, not the Java type: <association property="MyChildObject" resultMap="PrimaryKeyMap"/>

However, if MyChildObject is stored in the database as a separate table, nested inserts are not supported. You will need to call both inserts in Java. ResultMaps are for selects.

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. 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>