商品分類遞歸查詢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)寫一個方法使用遞歸來整理,傳遞參數爲categoryList
和parentId=0
(3)遍歷categoryList
得到每個category
中的id
(4)id
和parentId
進行比較,如果相等 放入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;
}