3-3 更新部门接口

SysDeptService

@Service
public class SysDeptService {
	
	@Autowired
	private SysDeptMapper sysDeptMapper;
	
	public void update(@Valid DeptParam param) {
		if(checkExist(param.getParentId(), param.getName(), param.getId())) {
			throw new ParamException("同一层级下存在相同名称的部门");
		}
		SysDept before = sysDeptMapper.selectByPrimaryKey(param.getId());
		// 使用 checkNotNull 方法进行校验会抛空指针异常,还可以用自定义异常说明的方法
		Preconditions.checkNotNull(before, "待更新的部门不存在");
		
		SysDept after = SysDept.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId())
	                					 .seq(param.getSeq()).remark(param.getRemark()).build();
	    after.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()), param.getParentId()));
	    after.setOperator("system-update");	// TODO
	    after.setOperateId("127.0.0.1");	// TODO
	    after.setOperateTime(new Date());
	    
	    updateWithChild(before, after);
	}
	
	// 更新子部门
	@Transactional
	public void updateWithChild(SysDept before, SysDept after) {
		String newLevelPrefix = after.getLevel();
		String oldLevelPrefix = before.getLevel();
		if(!after.getLevel().equals(before.getLevel())) {
			List<SysDept> oldChildDeptList = sysDeptMapper.getChildDeptListByLevel(oldLevelPrefix);
			if(CollectionUtils.isNotEmpty(oldChildDeptList)) {
				for(SysDept dept: oldChildDeptList) {
					String oldChildDeptLevel = dept.getLevel();
					if(oldChildDeptLevel.indexOf(oldLevelPrefix) == 0) {
						String newChildDeptLevel = newLevelPrefix + oldChildDeptLevel.substring(oldLevelPrefix.length());
	                    dept.setLevel(newChildDeptLevel);
					}
				}
				sysDeptMapper.batchUpdateLevel(oldChildDeptList);
			}
		}
		sysDeptMapper.updateByPrimaryKey(after);
	}
	
	// 检查同一层级下是否存在相同名称的部门
	private boolean checkExist(Integer parentId, String deptName, Integer deptId) {
		// TODO
		return false;
	}
	
	// 获取部门的 Level
	private String getLevel(Integer deptId) {
		SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
		if(dept == null) {
			return null;
		}
		return dept.getLevel();
	}
}

SysDeptMapper 添加 getChildDeptListByLevel、batchUpdateLevel 方法

<select id="getChildDeptListByLevel" resultMap="BaseResultMap">
  select
  <include refid="Base_Column_List" />
  from sys_dept
  where level like #{level} || '.%' 
</select>

<update id="batchUpdateLevel" parameterType="map">
  <foreach collection="oldChildDeptList" item="dept" separator=";">
    UPDATE sys_dept
    SET level = #{dept.level}
    WHERE id = #{dept.id}
  </foreach>
</update>

SysDeptController

@RequestMapping("/update")
@ResponseBody
public JsonData updateDept(DeptParam param) {
	sysDeptService.update(param);
	return JsonData.success();
}

注:对象不存在抛出异常函数(import com.google.common.base.Preconditions)

Preconditions.checkNotNull(object, "message");


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页