前言
collection(一对多) 元素的作用和association元素的作用差不多一样,事实上,它们非常类似,也是映射到JavaBean的某个“复杂类型” 属性,只不过这个属性是一个集合列表,即JavaBean内部嵌套一个复杂数据类型(集合)。和使用association元素一样,我们使用嵌套查询, 或者从连接中嵌套结果集。
示例
1、现有两张表,sys_dict_type和sys_dict_value,两表是一对多的关系,表结构如下图所示:
2、其中表sys_dict_type的实体如下:
@Data
public class DictType extends DataEntity<DictType> {
private String id; // 主键ID
private String type; // 类型
private List<DictValue> dictValueList = Lists.newArrayList(); // 子表列表
}
3、现有mapper方法查询sys_dict_type表数据:
<resultMap id="BaseResultMap" type="com.cn.modules.sys.entity.DictType" >
<id column="id" property="id" jdbcType="VARCHAR" />
<result column="type" property="type" jdbcType="VARCHAR" />
<collection property="dictValueList" javaType="java.util.ArrayList" ofType="com.cn.modules.sys.entity.DictValue"
select="com.cn.modules.sys.mapper.DictValueMapper.getDictValueByType"
column="{dict_type_id=id}" />
</resultMap>
<select id="getDict" resultMap="BaseResultMap">
select * from sys_dict_type
<where>
</where>
</select>
其中:
dict_type_id是定义的变量名, id是主表的字段id/sort 多个参数 column="{dict_type_id=id,xx=xx}",
先查出主表的结果, 然后主表记录数是几 就执行几次 collection 的select,
javaType写不写都行 mybatis会自行匹配,
select的值: 对应xml的namespace + 对应xml中的代码片段的id,
column作为select语句的参数传入,如果只传一个参数id可以简写: column="id"
4、最后是另一个xml中的getDictValueByType方法:
<sql id="dictValueColumns">
a.id AS "id",
a.label AS "label",
a.value AS "value",
a.sort AS "sort",
a.dict_type_id AS "dictType.id",
a.create_by AS "createBy.id",
a.create_date AS "createDate",
a.update_by AS "updateBy.id",
a.update_date AS "updateDate",
a.del_flag AS "delFlag"
</sql>
<select id="getDictValueByType" resultType="DictValue">
SELECT
<include refid="dictValueColumns"/>
FROM
sys_dict_value a
<where>
a.dict_type_id = #{dict_type_id}
</where>
ORDER BY cast(a.sort as UNSIGNED INTEGER)
</select>
其中:
a、变量名 dict_type_id 对应上文的 dict_type_id
b、如果上文中 collection只传一个参数column="id",只要类型匹配,在这里随便写个变量名就可以取到值,如 #{xyz}
至此功能实现。