Search code examples
javaxmlmappingmybatisibatis

MyBatis: How do I store Multiple Values from Query?


In my AppMapper.xml, I have a query like:

<select id="getCompleteDetails" parameterType="Map" resultType="String">
  SELECT * FROM PersonProfile WHERE ID = #{id}
</select>

Let's say it's going to return Name, Address, Age, Profession which are all strings. Is it correct that I use this?

<select id="selectPerson" parameterType="int" resultType="String">

or since there are multiple values to be received it should be something like

<select id="selectPerson" parameterType="int" resultMap="PersonProfileObj">

If I use "resultMap=PersonProfileObj", I know I need to create the resultMap like

<resultMap type="com.test.PersonProfileObj" id="PersonProfileObj">
 <result property="Name" column="Name">
<result property="Address" column="Address">
<result property="Age" column="Age">
<result property="Profession" column="Profession">
</resultMap>

//Is my resultMap correct?

*Im asking whether to use resultType=String or resultMap"PersonProfileObj"

Is my understanding correct?


Solution

  • resultType specifies the type of the object (or the element of the list if multiple objects are returned) that is returned by the given mapped SQL statement. If you specify resultType="String" the query should return exactly one field of type string.

    If you need to return multiple fields you can either:

    1. create an object and map these fields to object properties.
    2. return a map. In this case each field in the row will be an entry in the map with key equal to column name and value equal to field value.

    When you return an object you may use default mapping which sets properties of the object which correspond to column names or you can specify resultMap which allows to set column -> property mapping in more flexible way.

    Note also that there is autoMapping attribute on resultMap which maps columns implicitly to the properties with the same names, so in your example given that columns have the same names as properties it would suffice to have this mapping:

    <resultMap type="com.test.PersonProfileObj" id="PersonProfileObj" autoMapping="true">
    </resultMap>
    

    Note also that you usually want to have the id specified for the result map especially if the query is used in the collections/associations mapping or have joins.