以问题推动学习之——Mybatis(1)
collection
需求
将上表中相同to_platform对应的flow_record_cnt变成ArrayList,如下表所示。
解决
由于mybatis没有ArrayList类型,因此选用collection进行聚合。
<resultMap id="test" type="TbPlatformFlowStatsDO">
<id column="to_platform" jdbcType="VARCHAR" property="toPlatform" />
<collection
property="test"
javaType="ArrayList"
jdbcType="BIGINT"
ofType="Long">
<id column="flow_record_cnt" jdbcType="BIGINT" property="flowRecordCnt" />
</collection>
</resultMap>
<select id="selectTest" resultMap="test">
select to_platform, flow_record_cnt from tb_platform_flow_stats ;
</select>
结果如下图:
深入理解
再次回看上述代码,可以发现<id column=“to_platform” jdbcType=“VARCHAR” property=“toPlatform”//>与collection中的<id column=“flow_record_cnt” jdbcType=“BIGINT” property=“flowRecordCnt” //>,自动带有聚合能力,相同的to_platform会聚合成为一组,对应的flow_record_cnt可以变为ArrayList类型。
但在这里需要注意2点:
- 只有result中的id行与collection中的id行可以聚合,换句话说,如果在to_platform下增加了一个id行,那么这就是联合聚合(同时满足这两个条件,才将collection的值放在一个ArrayList中),但是如果这一行不是id,而是result,那么这一行不会和第一行联合聚合,它的值如果不唯一,那么你可能获取的值是随机的(一般是第一行的值,需要注意)。
<resultMap id="test" type="TbPlatformFlowStatsDO">
<id column="to_platform" jdbcType="VARCHAR" property="toPlatform" />
<id(result) column="stat_time" jdbcType="VARCHAR" property="statTime" />
<collection
property="test"
javaType="ArrayList"
jdbcType="BIGINT"
ofType="Long">
<id column="flow_record_cnt" jdbcType="BIGINT" property="flowRecordCnt" />
</collection>
</resultMap>
- 自定义类
如果你想自定义collection类,那么将ofType中的值改为自定义的类即可,不过你需要注意的是,这个自定义类需要是public类,不然没法调用。
具体的操作可以查看mybatis xml的映射操作