旧代码:
public void deptAddRegions(Long userId, Long deptId, String regionIds) {
//分配区域之前,先将原来分配的区域删除,即状态变为2
this.deleteDeptRegions(deptId);
// 如果regionIds不为空,插入记录
if (regionIds != null || !regionIds.equals("")) {
String[] regionIdList = regionIds.split(",");
for (String s : regionIdList) {
//首先根据区域id,查询区域实体信息
SysRegionEntity regionEntity = sysRegionService.getById(Long.parseLong(s));
SysDeptRegionEntity sysDeptRegion = new SysDeptRegionEntity();
sysDeptRegion.setDeptId(deptId);
sysDeptRegion.setRegionId(regionEntity.getOid());
sysDeptRegion.setRegionCode(regionEntity.getRegionCode());
sysDeptRegion.setTStatus(0);
this.save(sysDeptRegion);
}
}
}
优化后的逻辑:
public void deptAddRegions(Long userId, Long deptId, String regionIds) {
List<SysRegionEntity> regionEntityList = sysRegionService.getBydeptId(deptId);
List<String> oldRegionIds = new ArrayList<>();
for (SysRegionEntity sysRegionEntity : regionEntityList) {
oldRegionIds.add(sysRegionEntity.getOid().toString());
}
// 如果regionIds不为空,插入记录
if (regionIds != null || !regionIds.equals("")) {
String[] regionIdList = regionIds.split(",");
List<String> newRegionIds = new ArrayList<>(Arrays.asList(regionIdList));
oldRegionIds.removeAll(newRegionIds);
//分配区域之前,先将原来分配的区域删除,即状态变为2
for (String s : oldRegionIds) {
this.updateStatusByDeptIdAndRegionId(deptId, Long.parseLong(s), 2);
}
SysDeptRegionEntity sysDeptRegion = null;
for (String s : regionIdList) {
//首先根据区域id,查询区域实体信息
SysRegionEntity regionEntity = sysRegionService.getById(Long.parseLong(s));
sysDeptRegion = this.queryByDeptIdAndRegionId(deptId, Long.parseLong(s));
if (sysDeptRegion == null) {
sysDeptRegion = new SysDeptRegionEntity();
}
sysDeptRegion.setDeptId(deptId);
sysDeptRegion.setRegionId(regionEntity.getOid());
sysDeptRegion.setRegionCode(regionEntity.getRegionCode());
sysDeptRegion.setTStatus(0);
this.saveOrUpdate(sysDeptRegion);
}
}
}
区别:
更改前:
- 删除原分配代码省事儿;
- 表存储数据大;
更改后:
- new对象的次数减少;
- 表存储记录减少;
还可以更加的优化,更加的优雅,不知你是否想到了呢?
评论前必须登录!
注册