controller: /** * 保存接口(新增和删除) */ @PostMapping ("/saveCategory") public Result saveCategory(@RequestBody BroadScopeSaveDTO dto) { broadScopeService.saveCategory(dto); return Result.success(); }
传参的dto:
@Data public class BroadScopeSaveDTO { /** * 主键 */ private Long id; /** * 类目名称 */ private String categoryName; /** * 排序 */ private Long sort; } service:
Result saveCategory(BroadScopeSaveDTO dto); impl:
/**
* 保存接口(新增或者删除)
*
* @param dto
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Result saveCategory(BroadScopeSaveDTO dto) {
//先判断传来的名字是否是重复的
long l = broadScopeMapper.countByName(dto.getCategoryName());
if (l>0){
//如果重复就报错,该分类已存在
throw new BusinessException(MessageConstant.CATEGORY_EXISTS);
}
//然后判断传来的id是否有值(有修改.无新增)
if (ObjectUtil.isNull(dto.getId())){
boolean b = broadScopeMapper.insertCategory(dto);
if (ObjectUtil.isNull(b)){
//插入失败,保存失败
throw new BusinessException(MessageConstant.SAVE_FAILED);
}
}else {
//修改,修改前要查找旧的名字
String byName = broadScopeMapper.findByName(dto.getId());
boolean b = broadScopeMapper.updateCategory(dto.getId(), dto.getCategoryName(), dto.getSort());
if (ObjectUtil.isNull(b)){
//修改失败
throw new BusinessException(MessageConstant.UPDATE_FAILED);
}
//批量替换,旧名字变成新名字
Boolean b1 = broadScopePromptMapper.updateByCategoryName(byName, dto.getCategoryName());
if (ObjectUtil.isNull(b1)){
//批量替换修改失败
throw new BusinessException(MessageConstant.UPDATE_FAILED);
}
}
return Result.success();
}
BroadScopeMapper
mapper:
/** * 根据分类名字查询个数 * @param categoryName * @return */ long countByName(String categoryName);
xml:
mapper:
/** * 新增分类 * @param dto * @return */ boolean insertCategory(BroadScopeSaveDTO dto);
xml:
mapper:
/** * 根据id查询分类名称 * @param id * @return */ String findByName(Long id);
xml:
mapper:
/** * 修改分类 * @param id * @param categoryName * @param sort * @return */ boolean updateCategory(Long id, String categoryName, Long sort);
xml:
update broadscope_prompt_category where id =#{id} category_name=#{categoryName}, sort=#{sort}
BroadScopePromptMapper
mapper:
/** * 批零替换名字 * @param * @param categoryName * @return */ Boolean updateByCategoryName(String name, String categoryName);
xml:
update broadscope_prompt category =#{categoryName} where category=#{name}
测试: