MyBatis 使用一对多查询一级分类下的所有二级分类以及子分类

实体类

  1. /**
  2. * 小美团:电商首页的三级分类列表
  3. * @author songjiaming
  4. * @date 2021/12/6 11:06 上午
  5. */
  6. @Data
  7. public class EcoHomeThirdCategoryListView {
  8. @ApiModelProperty("分类id")
  9. private Long id;
  10. @ApiModelProperty("分类名称")
  11. private String name;
  12. @ApiModelProperty("分类图标")
  13. private String icon;
  14. }
  1. /**
  2. * 小美团:电商首页更多分类(二级+三级)
  3. *
  4. * @author songjiaming
  5. * @date 2021/12/6 11:10 上午
  6. */
  7. @Data
  8. @JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
  9. public class EcoMoreCategoryListView {
  10. @ApiModelProperty("二级id")
  11. private Long id;
  12. @ApiModelProperty("二级name")
  13. private String name;
  14. @ApiModelProperty("分类列表")
  15. private List<EcoHomeThirdCategoryListView> children;
  16. }

DAO

  1. @Mapper
  2. public interface PmsProductCategoryMapper extends BaseMapper<PmsProductCategory> {
  3. /**
  4. * 小美团/电商:获取商品分类及其子分类
  5. */
  6. @Select("<script> " +
  7. " select id,name" +
  8. " from pms_product_category " +
  9. " where company_id = #{companyId} and parent_id = #{parentId} and show_status=1 " +
  10. " <if test='mchId != null'> and mch_id = #{mchId} </if>" +
  11. "</script>")
  12. @Results(value = {
  13. @Result(id = true, column = "id", property = "id"),
  14. @Result(column = "id",
  15. property = "children",
  16. many = @Many(
  17. select = "net.super0.merchant.meta.mapper.PmsProductCategoryMapper.getByParentIdByRetail",
  18. fetchType = FetchType.LAZY
  19. ))
  20. })
  21. List<EcoMoreCategoryListView> listWithChildrenByRetail(Integer companyId, Long mchId, Long parentId);
  22. /**
  23. * 小美团/电商:查询子分类
  24. * @param parentId
  25. * @return
  26. */
  27. @Select("<script>" +
  28. "select id,name,icon from pms_product_category where parent_id = #{parentId} and show_status=1 " +
  29. "order by sort" +
  30. "</script>")
  31. List<EcoHomeThirdCategoryListView> getByParentIdByRetail(Long parentId);
  32. }