update
public void update(DeptParam param) {
BeanValidator.check(param)
if(checkExist(param.getParentId(), param.getName(), param.getId())) {
throw new ParamException("同一层级下存在相同名称的部门")
}
SysDept before = sysDeptMapper.selectByPrimaryKey(param.getId())
//判断原来的部门,如果不存在 抛出异常
Preconditions.checkNotNull(before, "待更新的部门不存在")
//设置 值,包括ID,从参数中取出的
SysDept after = SysDept.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId())
.seq(param.getSeq()).remark(param.getRemark()).build()
//设置level,规则不变
after.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()), param.getParentId()))
after.setOperator(RequestHolder.getCurrentUser().getUsername())
after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()))
after.setOperateTime(new Date())
updateWithChild(before, after)
sysLogService.saveDeptLog(before, after)
}
private boolean checkExist(Integer parentId, String deptName, Integer deptId) {
return sysDeptMapper.countByNameAndParentId(parentId, deptName, deptId) > 0;
int countByNameAndParentId(@Param("parentId") Integer parentId, @Param("name") String name, @Param("id") Integer id);
参数有多个,可以统一写成map
<select id="countByNameAndParentId" parameterType="map" resultType="int">
SELECT count(1)
FROM sys_dept
WHERE name = #{name}
<if test="parentId != null">
AND parent_id = #{parentId}
</if>
<if test="id != null"> --添加的时候,没有ID,更新的时候,如果当前 不相等 的 还能查出,就是已经存在过了
AND id != #{id}
</if>
</select>
@Transactional
public void updateWithChild(SysDept before, SysDept after) {
String newLevelPrefix = after.getLevel();
String oldLevelPrefix = before.getLevel();
if (!after.getLevel().equals(before.getLevel())) {
String curLevel = before.getLevel() + "." + before.getId();
List<SysDept> deptList = sysDeptMapper.getChildDeptListByLevel(curLevel + "%");
if (CollectionUtils.isNotEmpty(deptList)) {
for (SysDept dept : deptList) {
String level = dept.getLevel();
if (level.equals(curLevel) || level.indexOf(curLevel + ".") == 0) {
level = newLevelPrefix + level.substring(oldLevelPrefix.length());
dept.setLevel(level);
}
}
sysDeptMapper.batchUpdateLevel(deptList);
}
}
sysDeptMapper.updateByPrimaryKey(after);
}
List<SysDept> getChildDeptListByLevel(@Param("level") String level);
<select id="getChildDeptListByLevel" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from sys_dept
WHERE level like #{level}
</select>
void batchUpdateLevel(@Param("sysDeptList") List<SysDept> sysDeptList);
<update id="batchUpdateLevel" parameterType="map">
<foreach collection="sysDeptList" item="dept" separator=";">
UPDATE sys_dept
SET level = #{dept.level}
WHERE id = #{dept.id} //根据dept的id更新
</foreach>
</update>
@Getter
@Setter
@ToString
public class DeptParam {
private Integer id;
@NotBlank(message = "部门名称不可以为空")
private String name;
private Integer parentId = 0;
@NotNull(message = "展示顺序不可以为空")
private Integer seq;
@Length(max = 150, message = "备注的长度需要在150个字以内")
private String remark;
}
- 这里感觉用oracle的树查询会更简单,用了level 增加了很多没必要的麻烦