(这是JDK1.7写法,JDK1.8兼容,1.8后有新写法)
1.创建实体类package com.assionx.logic.product.enitity;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class Category implements Serializable {
private long catId;
private String name;
private Long parentCid;
private Integer catLevel;
private Integer showStatus;
private Integer sort;
private String icon;
private String productUnit;
private Integer productCount;
//该属性不在数据库内
private List children;
}
2.创建Myabtis查询接口
package com.assionx.logic.product.mapper;
import com.assionx.logic.product.enitity.Category;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@Mapper
public interface CategoryMapper {
List getCategories();
}
3.创建Service
package com.assionx.logic.product.service;
import com.assionx.logic.product.enitity.Category;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface CategoryService {
List getCategoryTree();
}
5.实现分级业务
package com.assionx.logic.product.service.impl;
import com.assionx.logic.product.enitity.Category;
import com.assionx.logic.product.mapper.CategoryMapper;
import com.assionx.logic.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import static com.assionx.logic.product.config.ProductConfig.KEY_LIST;
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired
CategoryMapper categoryMapper;
@Override
public List getCategoryTree() {
List categories=categoryMapper.getCategories();
List categoryList=new ArrayList<>();
for(Category category:categories){
if(category.getCatLevel()==1){
category.setChildren(getChildren(category,categories));
categoryList.add(category);
}
}
return categoryList;
}
private List getChildren(Category parentCategory,List all){
List children=new ArrayList<>();
for(Category category:all){
if(parentCategory.getCatId()== category.getParentCid()){
children.add(category);
}
}
parentCategory.setChildren(children);
for (Category category:children){
getChildren(category,all);
}
return children;
}
}
6.附加数据库结构图(MySQL)
(name,parenrt_cid,cate_level)必须添加
create table pms_category ( cat_id bigint not null auto_increment comment '分类id', name char(50) comment '分类名称', parent_cid bigint comment '父分类id', cat_level int comment '层级', show_status tinyint comment '是否显示[0-不显示,1显示]', sort int comment '排序', icon char(255) comment '图标地址', product_unit char(50) comment '计量单位', product_count int comment '商品数量', primary key (cat_id) );



