设计及封装无限层级的树状结构
需求:电商项目中,在商品的品类管理模块,会涉及到递归调用出该节点的所有子节点的操作。
数据表设计:
Category:
public class Category {
private Integer id;
private Integer parentId;
private String name;
private Boolean status;
private Integer sortOrder;
private Date createTime;
private Date 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!=null?!id.equals(category.id):category.id!=null);
}
@Override
public int hashCode(){
return id!=null?id.hashCode():0;
}
}
Controller:
/**
* 根据传的categoryId获取当前categoryId下边节点的category信息(平级,无递归)
* @param session
* @param categoryId
* @return
*/
@RequestMapping("get_category.do")
@ResponseBody
public ServerResponse getChildrenParallelCategory(HttpSession session,
@RequestParam(value = "categoryId",defaultValue = "0") Integer categoryId){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请先登录");
}
if(iUserService.checkAdminRole(user).isSuccess()){
//查询子节点的category信息,并且不递归,保持平级
return iCategoryService.getChildrenParallelCategory(categoryId);
}else {
return ServerResponse.createByErrorMessage("无权限操作,需要管理员权限");
}
}
/**
* 获取当前的categoryId并且递归查询它的子节点的categoryId
* @param session
* @param categoryId
* @return
*/
@RequestMapping("get_deep_category.do")
@ResponseBody
public ServerResponse getCategoryAndDeepChildrenCategory(HttpSession session,
@RequestParam(value = "categoryId",defaultValue = "0") Integer categoryId){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请先登录");
}
if(iUserService.checkAdminRole(user).isSuccess()){
//查询当前节点的id和递归子节点的id
return iCategoryService.selectCategoryAndChildrenById(categoryId);
}else {
return ServerResponse.createByErrorMessage("无权限操作,需要管理员权限");
}
}
ServiceImpl:
@Override
public ServerResponse<List<Category>> getChildrenParallelCategory(Integer categoryId){
List<Category> categoryList = categoryMapper.selectCategoryChildrenParentId(categoryId);
if(CollectionUtils.isEmpty(categoryList)){
logger.info("未找到当前分类的子分类");
}
return ServerResponse.createBySuccess(categoryList);
}
/**
* 递归查询本节点的id及其子孙节点的id:获取当前categoryId下的子节点,还要继续查找子节点是否还有子节点,及所有子孙节点
* 0-->10-->100
* 如果传0,会返回10和100
* 如果传10,会返回100
* @param categoryId
* @return
*/
@Override
public ServerResponse<List<Integer>> selectCategoryAndChildrenById(Integer categoryId){
HashSet<Category> categorySet = Sets.newHashSet();
findChildCategory(categorySet,categoryId);
List<Integer> categoryIdList = Lists.newArrayList();
if(categoryId!=null){
for(Category categoryItem : categorySet){
categoryIdList.add(categoryItem.getId());
}
}
return ServerResponse.createBySuccess(categoryIdList);
}
递归算法:
/**
* 为了使使用set集合不重复,需要重写hashcode和equals方法
* 递归算法:算出子节点
* @param categorySet
* @param categoryId
* @return
*/
private Set<Category> findChildCategory(Set<Category> categorySet,Integer categoryId){
Category category = categoryMapper.selectByPrimaryKey(categoryId);
if(category!=null){
categorySet.add(category);
}
//查找子节点,递归算法一定要有一个退出的条件
List<Category> categoryList = categoryMapper.selectCategoryChildrenParentId(categoryId);
for(Category categoryItem:categoryList){
findChildCategory(categorySet,categoryItem.getId());
}
return categorySet;
}
mapper:
public interface CategoryMapper {
int deleteByPrimaryKey(Integer id);
int insert(Category record);
int insertSelective(Category record);
Category selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Category record);
int updateByPrimaryKey(Category record);
/**
* 根据categoryId获取孩子节点的category信息
* @param parentId
* @return
*/
List<Category> selectCategoryChildrenParentId(Integer parentId);
}
xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hcxmall.dao.CategoryMapper" >
<resultMap id="BaseResultMap" type="com.hcxmall.pojo.Category" >
<constructor>
<idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="parent_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="name" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="status" jdbcType="BIT" javaType="java.lang.Boolean" />
<arg column="sort_order" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="create_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
<arg column="update_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
</constructor>
</resultMap>
<sql id="Base_Column_List" >
id, parent_id, name, status, sort_order, create_time, update_time
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from mmall_category
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from mmall_category
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.hcxmall.pojo.Category" >
insert into mmall_category (id, parent_id, name,
status, sort_order, create_time,
update_time)
values (#{id,jdbcType=INTEGER}, #{parentId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},
#{status,jdbcType=BIT}, #{sortOrder,jdbcType=INTEGER},now(),
now())
</insert>
<insert id="insertSelective" parameterType="com.hcxmall.pojo.Category" >
insert into mmall_category
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="parentId != null" >
parent_id,
</if>
<if test="name != null" >
name,
</if>
<if test="status != null" >
status,
</if>
<if test="sortOrder != null" >
sort_order,
</if>
<if test="createTime != null" >
create_time,
</if>
<if test="updateTime != null" >
update_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="parentId != null" >
#{parentId,jdbcType=INTEGER},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="status != null" >
#{status,jdbcType=BIT},
</if>
<if test="sortOrder != null" >
#{sortOrder,jdbcType=INTEGER},
</if>
<if test="createTime != null" >
now(),
</if>
<if test="updateTime != null" >
now(),
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.hcxmall.pojo.Category" >
update mmall_category
<set >
<if test="parentId != null" >
parent_id = #{parentId,jdbcType=INTEGER},
</if>
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="status != null" >
status = #{status,jdbcType=BIT},
</if>
<if test="sortOrder != null" >
sort_order = #{sortOrder,jdbcType=INTEGER},
</if>
<if test="createTime != null" >
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null" >
update_time = now(),
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.hcxmall.pojo.Category" >
update mmall_category
set parent_id = #{parentId,jdbcType=INTEGER},
name = #{name,jdbcType=VARCHAR},
status = #{status,jdbcType=BIT},
sort_order = #{sortOrder,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = now()
where id = #{id,jdbcType=INTEGER}
</update>
<select id="selectCategoryChildrenParentId" resultMap="BaseResultMap" parameterType="int">
SELECT <include refid="Base_Column_List"/>
FROM mmall_category
WHERE parent_id = #{parentId}
</select>
</mapper>