类似商品分类、部门树相关构建在开发中必不可少,既可以通过mybatis,也可以通过java8的新特性来实现。
此时只需要蛋糕和点心,然后三级分类为一个List
构造一个VO
public class CategoryVO {
private Integer id;
private String name;
private String type;
private Integer fatherId;
// 三级分类vo list
private List<SubCategoryVO> subCatList;
}
可以直接通过collection 标签实现 在sql层面将其封装成VO
<resultMap id="myCategoryVO" type="com.imooc.pojo.vo.CategoryVO">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="type" property="type"/>
<result column="fatherId" property="fatherId"/>
<!--
collection 标签:用于定义关联的list集合类型的封装规则
property:对应三级分类的list属性名
ofType:集合的类型,三级分类的vo
-->
<collection property="subCatList" ofType="com.imooc.pojo.vo.SubCategoryVO">
<id column="subId" property="subId"/>
<result column="subName" property="subName"/>
<result column="subType" property="subType"/>
<result column="subFatherId" property="subFatherId"/>
</collection>
</resultMap>
<select id="getSubCatList" resultMap="myCategoryVO" parameterType="int">
SELECT
f.id as id,
f.`name` as `name`,
f.type as type,
f.father_id as fatherId,
c.id as subId,
c.`name` as subName,
c.type as subType,
c.father_id as subFatherId
FROM
category f
LEFT JOIN
category c
on
f.id = c.father_id
WHERE
f.father_id = #{
rootCatId}
</select>
如下为java8实现,直接使用分组即可,变成键值对的形式
List<TargetCustomerProductDO> targetCustomerProductDOS = targetCustomerProductService.selectCustomerProductByTargetId(targetId);
Map<String,List<TargetCustomerProductDO>> map= targetCustomerProductDOS.stream()
.collect(Collectors.groupingBy(TargetCustomerProductDO::getCompanyName));
根据不用需求可以选用不同方式