All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.kasinf.framework.rest.web.service.BaseTreeService Maven / Gradle / Ivy

The newest version!
package com.kasinf.framework.rest.web.service;

import cn.hutool.core.util.StrUtil;
import com.kasinf.framework.rest.eneity.type.TreeEntity;
import com.kasinf.framework.rest.repository.BaseTreeRepository;
import org.springframework.util.StringUtils;

import java.io.Serializable;

/**
 * 通用树型结构逻辑处理类
 *
 * @author lkhsh
 */
public interface BaseTreeService extends BaseService {

    /**
     * 获取存储库,调用父级的方法
     *
     * @return BaseTreeRepository
     */
    default BaseTreeRepository getBaseTreeRepository() {
        return (BaseTreeRepository) getBaseRepository();
    }

    /**
     * 在创建之前要调用makeSelfAsNewParentIds()构造节点路径
     *
     * @param t 要保存的实体
     * @return true
     */
    @Override
    @SuppressWarnings("all")
    default boolean beforeCreate(T t) {
        T parent = null;
        if (t.getParent() != null && !StringUtils.isEmpty(t.getParent().getId())) {
            parent = getBaseRepository().findOne((ID) t.getParent().getId());
            t.setParent(parent);
        }
        if (t.getWeight() == null) {
            if (parent == null || StringUtils.isEmpty(t.getParent().getId())) {
                t.setWeight(getBaseTreeRepository().findRootNextWeight());
            } else {
                t.setWeight(getBaseTreeRepository().findNextWeight(parent));
            }
        }
        return true;
    }

    /**
     * 获取主键后,生成
     *
     * @param t 保存后的实体
     * @return 生成节点路径后的实体
     */
    @Override
    default T afterCreate(T t) {
        t.makeSelfAsNewParentIds();
        return getBaseRepository().save(t);
    }

    /**
     * 在更新之前要调用makeSelfAsNewParentIds()构造节点路径
     *
     * @param t 要保存的实体
     * @return true
     */
    @Override
    @SuppressWarnings("all")
    default boolean beforeUpdate(T t) {
        if (t.getParent() != null) {
            T parent = getBaseRepository().findById((ID) t.getParent().getId()).get();
            t.setParent(parent);
        }
        return true;
    }

    /**
     * 更新节点路径
     *
     * @param t 更新之后的实体
     * @return 生成节点路径后的实体
     */
    @Override
    default T afterUpdate(T t) {
        String oldParentIds = t.getParentIds();
        t.makeSelfAsNewParentIds();
        String newParentIds = t.getParentIds();
        // 更新所有子节点的路径,但是需要手动调整weight
        getBaseTreeRepository().updateParentIds(newParentIds, oldParentIds);
        return getBaseRepository().save(t);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy