Mapping a list of strings as <collection> 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:

idstr
1A
1B

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值