首先构建分类树形结构,再通过接口展示分类并关联商品查询。使用Category类表示分类,包含id、名称、父级id及子分类列表;通过数据库表存储分类数据,利用Map建立分类映射关系,遍历构建父子结构形成分类树;在Spring Boot中提供REST接口返回完整分类树;商品表关联分类id,查询时根据当前分类及其子分类id列表获取对应商品,确保浏览时数据准确呈现。

实现商品分类浏览功能,核心是构建清晰的分类结构并提供高效的查询接口。Java中可通过面向对象设计结合数据库操作来完成这一需求。重点在于分类的层级管理、数据关联与前端展示的衔接。
设计分类实体类
商品分类通常具有父子层级关系,比如“电子产品”下有“手机”、“电脑”等子类。可以定义一个分类类 Category 来表示这种树形结构。
示例代码:
public class Category {
private Long id;
private String name;
private Long parentId; // 父分类ID,根分类为null或0
private List<Category> children = new ArrayList<>();
private Integer sortOrder; // 排序字段
// 构造方法、getter和setter省略
}
这个类支持递归嵌套,便于构建多级目录树。
从数据库加载分类数据
分类数据一般存储在数据库中。常见的表结构包含 id、name、parent_id、sort_order 等字段。
立即学习“Java免费学习笔记(深入)”;
使用JDBC或MyBatis等框架查询所有分类,并组织成树形结构。
public List<Category> buildCategoryTree(List<Category> categories) {
Map<Long, Category> categoryMap = new HashMap<>();
List<Category> rootCategories = new ArrayList<>();
// 先将所有分类放入map,便于查找
for (Category c : categories) {
categoryMap.put(c.getId(), c);
}
// 构建父子关系
for (Category c : categories) {
if (c.getParentId() == null || c.getParentId() == 0) {
rootCategories.add(c);
} else {
Category parent = categoryMap.get(c.getParentId());
if (parent != null) {
parent.getChildren().add(c);
}
}
}
return rootCategories;
}
这样就能得到一个完整的分类树,可用于页面展示。
提供分类浏览接口
在Web应用中,可以通过Spring Boot暴露REST接口供前端调用。
@RestController
@RequestMapping("/api/categories")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@GetMapping
public List<Category> getAllCategories() {
List<Category> categories = categoryService.getAllCategories();
return categoryService.buildCategoryTree(categories);
}
}
前端请求该接口后,即可渲染出多级分类菜单。
关联商品数据查询
用户点击某个分类时,需列出该分类下的商品。可在商品表中添加 category_id 字段。
查询时根据分类ID获取商品列表,注意考虑子分类中的商品是否也应显示。
- 若只查当前分类:直接按 category_id 查询
- 若包含子分类:先递归获取该分类及其所有子类ID,再用 IN 查询商品
例如:
public List<Product> getProductsByCategory(Long categoryId) {
List<Long> allCategoryIds = getAllChildCategoryIds(categoryId);
allCategoryIds.add(categoryId); // 包含自身
return productMapper.selectByCategoryIds(allCategoryIds);
}
基本上就这些。结构清晰、数据准确是关键。










