分类列表
列表实体类:
@EqualsAndHashCode(callSuper = true) @Data @TableName("cms_category") public class Category extends Model<Category> { /** * 类别表栏目ID */ @ApiModelProperty(value = "类别表栏目ID") @TableId(value = "`id`",type = IdType.AUTO) private long id; /** * 父级栏目ID */ @ApiModelProperty(value = "父级栏目ID") @TableField(value = "`pid`") private String pId; /** * 栏目名称 */ @ApiModelProperty(value = "栏目名称") @TableField(value = "`name`") private String name; /** * 是否启用(0 否 1 是) */ @ApiModelProperty(value = "是否启用(0 否 1 是)") @TableField(value = "`is_enable`") private String isEnable; /** * 排序 */ @ApiModelProperty(value = "排序") @TableField(value = "`sort`") private String sort; /** * 创建时间 */ @ApiModelProperty(value = "创建时间") @TableField(value = "`create_time`") private String createTime; /** * 子节点 */ @ApiModelProperty(value = "子节点") @TableField(exist = false) private List<Category> children; }controller层:
@RestController @RequestMapping("/web/category") @Api(tags = {"后台接口-文章分类相关接口"}) public class CategoryController { @Autowired CategoryService categoryService; @PostMapping(value = "getTree") @ApiOperation("查询树形结构") public CommonResult getTreeByPid() { List<Category> category= categoryService.getTree(0L); return CommonResult.success(category); } }service接口
public interface CategoryService extends IService<Category> { /** * 通过id来查找类别 * @param id * @return */ Category findByCategoryId(Long id); /** * 通过pId查询列表结构 */ List<Category> getTree(Long pId); }service实现类
@Service public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService { @Autowired CategoryMapper categoryMapper; @Override public Category findByCategoryId(Long id) { return categoryMapper.findByCategoryId(id); } @Override public List<Category> getTree(Long pId){ QueryWrapper<Category> wrapper = new QueryWrapper<>(); wrapper.eq("pid", pId); List<Category> list = categoryMapper.selectList(wrapper); for (Category category : list) { List<Category> children = getTree(category.getId()); if (CollUtil.isEmpty(children)) { continue; } category.setChildren(children); } return list; } }主要是通过构造器查询查询一个列表,然后循环,递归的查找子节点,最终返回树形结构