MyBatis|Java8 自连接查询子分类

在这里插入图片描述
类似商品分类、部门树相关构建在开发中必不可少,既可以通过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));

根据不用需求可以选用不同方式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunywz

~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值