Mapping a list of strings as in XML could be more intuitive

The bahviour observed when mapping a string collection does not feel very obvious to me. I only figured out how thanks to this thread:

For the following SQL statement:

select id, str from testTable

where testTable contains:

id str
1 A
1 B

And where we expect a single result row with the content:

{"id": 1, "str": ["A", "B"]}

this must be mapped as follows:

<resultMap id="stringsResultOk" type="java.util.Map">
    <id column="id" property="id" />
    <collection property="strings" ofType="java.lang.String" javaType="list">
        <result column="str" />
    </collection>
</resultMap>

I'd usually expect that the <result> tag in the collection would refer to a property of an item in the collection which of course would not make any sense for items of type string. However it works perfectly fine.

On the otherhand this mapping:

<resultMap id="stringsWrongColumnMapping" type="java.util.Map">
    <id column="id" property="id" />
    <collection property="strings" column="str" ofType="java.lang.String" javaType="list" />
</resultMap>

would seem to be the natural choice for me, however the "column" attribute seems to have no effect. (It is only used for Nested Select for Collection?). Instead this mapping will just be filled with a value from the id column which does seem rather random.

The following mapping won't work either:

<resultMap id="stringsMissingJavaType" type="java.util.Map">
    <id column="id" property="id" />
    <collection property="strings" ofType="java.lang.String">
        <result column="str" />
    </collection>
</resultMap>

This does not work because the collection does not specify a javaType for the collection. Instead the tag will generate just a single plain string which is quite a surprise because it is most definitly not a collection as the tag <collection> would suggest.

I suggest to either change the behaviour of the later two mapping types or throw some helpful exceptions that point one to the right direction about what is wrong. And maybe extend the documentation about how the mapping for collection of simple types works (if I haven't accidentially missed it).

See some tests that illustrate my findings with some real code here:

https://github.com/yankee42/mybatis-string-collection

 

来源:https://github.com/mybatis/mybatis-3/issues/364

你可能感兴趣的:(Mapping a list of strings as in XML could be more intuitive)