项目中使用mybatis查询结果,有时需要嵌套对象,即返回对象中要有list集合,对象含有子集集合(查询的主表与关联子表数据一对多关系)
java对象:
public class Typegroup extends ResultBaseDataObject {
@ExcelIgnore
@ApiModelProperty(value = "主键")
private Long id;
@ExcelProperty(value = "分组代码")
@ApiModelProperty(value = "分组代码")
private String typegroupCode;
@ExcelProperty(value = "分组名称")
@ApiModelProperty(value = "分组名称")
private String typegroupName;
@ExcelIgnore
@ApiModelProperty(value = "父级分组id")
private String parentId;
@ExcelIgnore
@ApiModelProperty(value = "父级分组代码")
private String parentTypegroupCode;
@ExcelProperty(value = "父级分组名称")
@ApiModelProperty(value = "父级分组名称")
private String parentTypegroupName;
@ExcelIgnore
@ApiModelProperty(value = "排序")
private int sort;
/**
* 是否是多级节点,1 :代表多级节点 默认为空或者为0
*/
@ExcelIgnore
private String isManyTop;
@ExcelIgnore
private String isDown;
@ExcelIgnore
private String isMany;
@ExcelIgnore
private List<TypePojo> typeList;
}
mybatis配置文件:使用 <collection>标签配置子对象映射
<resultMap id="typegroupResultMap" type="com.unism.pojo.basicData.Typegroup">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="typegroup_code" jdbcType="VARCHAR" property="typegroupCode" />
<result column="typegroup_name" jdbcType="VARCHAR" property="typegroupName" />
<result column="is_many" jdbcType="VARCHAR" property="isMany" />
<result column="sort" jdbcType="VARCHAR" property="sort" />
<result column="parent_typegroup_code" jdbcType="VARCHAR" property="parentTypegroupCode" />
<collection property="typeList" javaType="list" ofType="com.unism.pojo.basicData.TypePojo">
<result column="typegroup_id" jdbcType="BIGINT" property="typegroupId" />
<result column="type_code" jdbcType="VARCHAR" property="typeCode" />
<result column="type_name" jdbcType="VARCHAR" property="typeName" />
</collection>
</resultMap>
查询sql:
<select id="queryTypeListByParentTypegroupCode" parameterType="java.lang.String" resultMap="typegroupResultMap">
SELECT
a.id, a.typegroup_code,a.typegroup_name,a.parent_typegroup_code,b.typegroup_id,b.type_code,b.type_name
FROM
tbl_service_typegroup a ,
tbl_service_type b
WHERE
a.id = b.typegroup_id
AND a.parent_typegroup_code = #{parentTypegroupCode,jdbcType=VARCHAR}
ORDER BY
a.sort,
b.sort
</select>
但是有的时候返回解决不是我们想要的格式,比如有三个Typegroup对象,没有Typegroup对象中有四个TypePojo子对象
想要的结果是List<Typegroup>里有三个Typegroup对象,每一个Typegroup对象中有一个List<TypePojo>,list中有四个TypePojo对象,但是返回结果是一个List<Typegroup>里有12个Typegroup对象
产生原因是:没有设置主键id,要在返回结果resultMap中设置主键映射:
<id column="id" jdbcType="BIGINT" property="id" />
mybatis要依照相同的主键进行映射返回对象,封装数据