商品分类递归查询Tree结构展示

商品分类递归查询Tree结构展示

商品分类数据结构:

create table tb_category(
	id int primary key auto_increment,
    name varchar(50),
    goods_num int,
    is_show char(1),
    is_menu char(1),
    seq int,
    parent_id int,
    template_id int
);

parent_id 父ID,自关联。

import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
 * category实体类
 * @author Administrator
 *
 */
@Table(name="tb_category")
public class Category implements Serializable{

	@Id
	private Integer id;//分类ID

	private String name;//分类名称

	private Integer goodsNum;//商品数量

	private String isShow;//是否显示

	private String isMenu;//是否导航

	private Integer seq;//排序

	private Integer parentId;//上级ID

	private Integer templateId;//模板ID

	//setXxx/getXxx 

}

前后端约定数据格式:

[
	{
        name:"一级菜单",
        menus:[
            {
                name:"二级菜单",
                menus:[
                   {
                        name:"三级菜单"
                   },
                    .........
                ]
            }
        ]
    }
 
]
 //这种数据格式集合里面嵌套Map.

1.先查询出符合条件(符合条件是is_show=1,表示展示)的数据 List<Category> categoryList

2.通过递归形式进行数据整理。

​ (1)用什么数据类型进行接收:List<Map>

​ (2)写一个方法使用递归来整理,传递参数为categoryListparentId=0

​ (3)遍历categoryList 得到每个category中的id

​ (4)idparentId进行比较,如果相等 放入Map,在放入"menus"的时候在调用这个方法,此时就是在递归了。

Mapp用的是通用Mapper/数据库使用的是Mysql

 public List<Map> findCategoryTree() { 
	//先查询符合条件的所有分类
    Example example=new Example(Category.class); 
    Example.Criteria criteria = example.createCriteria(); 
    criteria.andEqualTo("isShow","1");//1为显示 ;0 不显示 
    //排序
    example.setOrderByClause("seq"); 
    List<Category> categories = categoryMapper.selectByExample(example); 
	
    //parentId = 0   第一次 传递参数 0 表示一级, 查看表中的数据。
    return findByParentId(categories,0); 

}
//数据整理  使用递归
private List<Map> findByParentId(List<Category> categoryList, Integer 

parentId){ 

    List<Map> mapList=new ArrayList<Map>(); 

    for(Category category:categoryList){ 

        if(category.getParentId().equals(parentId)){ 

            Map map =new HashMap(); 

            map.put("name",category.getName()); 

            map.put("menus",findByParentId(categoryList,category.getId())); 

            mapList.add(map); 

        } 

    }

    return mapList; 

} 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值