This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
k18-ntcs-web-ntc/src/main/java/com/nis/web/service/TreeService.java
2017-12-29 16:18:40 +08:00

82 lines
2.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.nis.web.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.nis.domain.TreeEntity;
import com.nis.exceptions.ServiceException;
import com.nis.util.Reflections;
import com.nis.util.StringUtil;
import com.nis.util.StringUtils;
import com.nis.web.dao.TreeDao;
/**
* Service基类
* @author ThinkGem
* @version 2014-05-16
*/
public abstract class TreeService<D extends TreeDao<T>, T extends TreeEntity<T>> extends CrudService<D, T> {
public void save(T entity) {
@SuppressWarnings("unchecked")
Class<T> entityClass = Reflections.getClassGenricType(getClass(), 1);
// 如果没有设置父节点,则代表为跟节点,有则获取父节点实体
if (entity.getParent() == null || StringUtil.isEmpty(entity.getParentId())
|| "0".equals(entity.getParentId())){
entity.setParent(null);
}else{
entity.setParent(super.get(entity.getParentId()));
}
if (entity.getParent() == null){
T parentEntity = null;
try {
parentEntity = entityClass.getConstructor(Long.class).newInstance(0l);
} catch (Exception e) {
throw new ServiceException(e);
}
entity.setParent(parentEntity);
entity.getParent().setParentIds(StringUtils.EMPTY);
}
// 获取修改前的parentIds用于更新子节点的parentIds
String oldParentIds = entity.getParentIds();
// 设置新的父节点串
entity.setParentIds(entity.getParent().getParentIds()+entity.getParent().getId()+",");
// 保存或更新实体
super.save(entity);
// 更新子节点 parentIds
T o = null;
try {
o = entityClass.newInstance();
} catch (Exception e) {
throw new ServiceException(e);
}
o.setParentIds("%,"+entity.getId()+",%");
List<T> list = dao.findByParentIdsLike(o);
for (T e : list){
if (e.getParentIds() != null && oldParentIds != null){
e.setParentIds(e.getParentIds().replace(oldParentIds, entity.getParentIds()));
preUpdateChild(entity, e);
dao.updateParentIds(e);
}
}
}
/**
* 预留接口,用户更新子节前调用
* @param childEntity
*/
protected void preUpdateChild(T entity, T childEntity) {
}
}