1.递归算法
1.1查找当前节点及其子节点ID
1.1.1实体类
package com.mmall.pojo;
import java.util.Date;
import java.util.Objects;
public class Category {
private Integer id;
private Integer parentId;
private String name;
private Boolean status;
private Integer sortOrder;
private Date createTime;
private Date updateTime;
public Category(Integer id, Integer parentId, String name, Boolean status, Integer sortOrder, Date createTime, Date updateTime) {
this.id = id;
this.parentId = parentId;
this.name = name;
this.status = status;
this.sortOrder = sortOrder;
this.createTime = createTime;
this.updateTime = updateTime;
}
public Category() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Integer getSortOrder() {
return sortOrder;
}
public void setSortOrder(Integer sortOrder) {
this.sortOrder = sortOrder;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Category category = (Category) o;
return id.equals(category.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
说明数据库表为含有parentId的子节点,同时使用递归算法时,需要重新hashCode()和equals()方法,方法需保存不重复字段,这里保存的是id
1.1.2递归获取category实体对象
//递归算法,算出子节点
private Set<Category> findChileCategory(Set<Category> categorySet,Integer categoryId){
Category category=categoryMapper.selectByPrimaryKey(categoryId);
if(category!=null){
categorySet.add(category);
}
//查找子节点,递归算法一定有退出条件
List<Category> categoryList=categoryMapper.selectCategoryChildrenByParentId(categoryId);
for(Category categoryItem:categoryList){
findChileCategory(categorySet,categoryItem.getId());
}
return categorySet;
}
1.1.3递归获取相关的子id
/**
* 递归算法查询子节点的id及孩子节点的Id
* @param categoryId
* @return
*/
public List<Integer>selectCategoryAndChildrenById(Integer categoryId){
Set<Category> categorySet= Sets.newHashSet();
findChileCategory(categorySet,categoryId);
List<Integer> categoryIdList= Lists.newArrayList();
if(categoryId!=null){
for(Category categoryItem:categorySet){
categoryIdList.add(categoryItem.getId());
}
}
return categoryIdList;
}