設(shè)計(jì)及封裝無限層級的樹狀結(jié)構(gòu)
需求:電商項(xiàng)目中,在商品的品類管理模塊抄囚,會(huì)涉及到遞歸調(diào)用出該節(jié)點(diǎn)的所有子節(jié)點(diǎn)的操作绍撞。
數(shù)據(jù)表設(shè)計(jì):
category表.jpg
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:
/**
* 根據(jù)傳的categoryId獲取當(dāng)前categoryId下邊節(jié)點(diǎn)的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()){
//查詢子節(jié)點(diǎn)的category信息坡垫,并且不遞歸梭灿,保持平級
return iCategoryService.getChildrenParallelCategory(categoryId);
}else {
return ServerResponse.createByErrorMessage("無權(quán)限操作,需要管理員權(quán)限");
}
}
/**
* 獲取當(dāng)前的categoryId并且遞歸查詢它的子節(jié)點(diǎn)的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()){
//查詢當(dāng)前節(jié)點(diǎn)的id和遞歸子節(jié)點(diǎn)的id
return iCategoryService.selectCategoryAndChildrenById(categoryId);
}else {
return ServerResponse.createByErrorMessage("無權(quán)限操作堡妒,需要管理員權(quán)限");
}
}
ServiceImpl:
@Override
public ServerResponse<List<Category>> getChildrenParallelCategory(Integer categoryId){
List<Category> categoryList = categoryMapper.selectCategoryChildrenParentId(categoryId);
if(CollectionUtils.isEmpty(categoryList)){
logger.info("未找到當(dāng)前分類的子分類");
}
return ServerResponse.createBySuccess(categoryList);
}
/**
* 遞歸查詢本節(jié)點(diǎn)的id及其子孫節(jié)點(diǎn)的id:獲取當(dāng)前categoryId下的子節(jié)點(diǎn),還要繼續(xù)查找子節(jié)點(diǎn)是否還有子節(jié)點(diǎn)屿脐,及所有子孫節(jié)點(diǎn)
* 0-->10-->100
* 如果傳0涕蚤,會(huì)返回10和100
* 如果傳10,會(huì)返回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集合不重復(fù)的诵,需要重寫hashcode和equals方法
* 遞歸算法:算出子節(jié)點(diǎn)
* @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);
}
//查找子節(jié)點(diǎn)万栅,遞歸算法一定要有一個(gè)退出的條件
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);
/**
* 根據(jù)categoryId獲取孩子節(jié)點(diǎn)的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>