今天前端需要我提供一个树状数据接口。想到了mybatis有collection可以使用。
但是使用时,child数据一直为null
原代码如下:
<resultMap id="waresTypeTreeMap" type="WaresTypeTreeEntity">
<id column="pk_base_wares_type_id" property="id" jdbcType="BIGINT" />
<result column="wares_type_name" property="text" jdbcType="VARCHAR" />
<collection property="nodes" column="id" ofType="WaresTypeTreeEntity" select="queryTreeWaresTypeList" />
</resultMap>
<select id="queryTreeWaresTypeList" resultMap="waresTypeTreeMap">
select
t.pk_base_wares_type_id,
t.wares_type_name
from t_base_wares_type t
where t.parent_id =#{waresTypeId,jdbcType=BIGINT}
</select>
根据经验判断应该是collection的column没传值导致,然后走了很多弯路,发现都不行。
最后无意间把 result 里的column及property改成一致,发现有效。
于是发现问题所在:collection里的column应该传的是 result里的 column,而不是property。
虽然传property不报错,但是mybatis collection是在转换成VO对象前触发的。
也就是说id一直为null。故child也是null值。
修改后代码如下:
<resultMap id="waresTypeTreeMap" type="WaresTypeTreeEntity">
<id column="pk_base_wares_type_id" property="id" jdbcType="BIGINT" />
<result column="wares_type_name" property="text" jdbcType="VARCHAR" />
<collection property="nodes" column="pk_base_wares_type_id" ofType="WaresTypeTreeEntity" select="queryTreeWaresTypeList" />
</resultMap>