分类列表
大约 2 分钟项目实战前后端分离博客项目
需求
页面上需要展示分类列表,用户可以点击具体的分类查看
该分类下的文章列表。
注意: ①要求只展示有发布正式文章
的分类 ②必须是正常状态
的分类
分类表设计
CREATE TABLE `sf_category` (
`id` bigint(200) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL COMMENT '分类名',
`pid` bigint(200) DEFAULT '-1' COMMENT '父分类id,如果没有父分类为-1',
`description` varchar(512) DEFAULT NULL COMMENT '描述',
`status` char(1) DEFAULT '0' COMMENT '状态0:正常,1禁用',
`create_by` bigint(200) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_by` bigint(200) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`del_flag` int(11) DEFAULT '0' COMMENT '删除标志(0代表未删除,1代表已删除)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COMMENT='分类表';
/*Data for the table `sg_category` */
insert into `sf_category`(`id`,`name`,`pid`,`description`,`status`,`create_by`,`create_time`,`update_by`,`update_time`,`del_flag`) values (1,'java',-1,'wsd','0',NULL,NULL,NULL,NULL,0),(2,'PHP',-1,'wsd','0',NULL,NULL,NULL,NULL,0);
接口设计
请求地址:
/category/getCategoryList
请求方式:
GET
请求参数:无
响应格式:
{ "code": 200, "data": [ { "id": "1000", "name": "Java" } ], "msg": "操作成功" }
思路分析
- 文章表获取
正式文章
的分类id集合(注意去重)。 - 根据分类id,到分类表获取
正常状态
的分类名称。 - 封装返回
代码实现
使用插件easy-code生成entity、mapper、service

放到对应的包中。
controller
@RestController
@RequestMapping("/category")
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 获取分类集合
* @return 结果
*/
@GetMapping("/getCategoryList")
public ResponseResult getCategoryList(){
return categoryService.getCategoryList();
}
}
service
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
@Autowired
private ArticleService articleService;
@Override
public ResponseResult getCategoryList() {
// 查询正式文章的分类ID
LambdaQueryWrapper<Article> articleQueryWrapper = new LambdaQueryWrapper<>();
articleQueryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
List<Long> categoryIds = articleService.list(articleQueryWrapper)
.parallelStream()
.map(Article::getCategoryId)
.distinct()
.collect(Collectors.toList());
// 查询正常状态分类名称
List<Category> categories = listByIds(categoryIds).stream()
.filter(category -> SystemConstants.CATEGORY_STATUS_NORMAL.equals(category.getStatus()))
.collect(Collectors.toList());
// 封装数据
List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categories, CategoryVo.class);
return ResponseResult.okResult(categoryVos);
}
}
访问接口:
localhost:7777/category/getCategoryList
