使用SpringBoot实现分类管理和标签管理
1.在TypeRepository中添加接口,用来控制不能添加重复的分类:
Type findByName(String name);
2.在TypeService中增加方法接口:
Type saveType(Type type);
Type getTypeByName(String name);
void delete(Long id);
Type getType(Long id);
Type updateType(Long id,Type type);
在TypeServiceImpl中实现接口:
@Override
public Page listType(Pageable pageable) {
return typeRepository.findAll(pageable);
}
@Override
public Type saveType(Type type) {
return typeRepository.save(type);
}
@Override
public Type getTypeByName(String name) {
return typeRepository.findByName(name);
}
@Override
public void delete(Long id) {
typeRepository.deleteById(id);
}
@Override
public Type getType(Long id) {
return typeRepository.findById(id).orElse(null);
}
@Override
public Type updateType(Long id, Type type) {
Type type1 =typeRepository.findById(id).orElse(null);
if(type1==null){
System.out.println("未获得更新对象");
return null;
}
BeanUtils.copyProperties(type,type1);
return typeRepository.save(type1);
}
3.在TypeController中编写方法:
@GetMapping("/types/input")
public String input(Model model){
model.addAttribute("type",new Type());
return "admin/types-input";
}
@PostMapping("/types/add")
public String add(@Valid Type type, BindingResult result, RedirectAttributes attributes){
Type type1=typeService.getTypeByName(type.getName());
if(type1!=null){
result.rejectValue("name","nameError","不能添加重复分类");
}
if(result.hasErrors()){
return "admin/types-input";
}
Type type2=typeService.saveType(type);
if(type2==null){
attributes.addFlashAttribute("message","新增失败");
}else {
attributes.addFlashAttribute("message","新增成功");
}
return "redirect:/admin/types";
}
@RequestMapping("/types/{id}/delete")
public String delete(@PathVariable Long id,RedirectAttributes attributes){
typeService.delete(id);
attributes.addFlashAttribute("message","删除成功");
return "redirect:/admin/types";
}
@RequestMapping("/types/{id}/toUpdate")
public String toUpdate(@PathVariable Long id,Model model){
System.out.println("id:"+id);
model.addAttribute("type",typeService.getType(id));
System.out.println("根据id查得数据为:"+typeService.getType(id));
return "admin/types-input";
}
@RequestMapping("/types/update/{id}")
public String update(@Valid Type type,BindingResult result,@PathVariable Long id,RedirectAttributes attributes){
System.out.println("传入type:"+type);
Type type1=typeService.getTypeByName(type.getName());
if(type1!=null){
result.rejectValue("name","nameError","不能添加重复的分类");
}
if(result.hasErrors()){
return "admin/types-input";
}
Type type2=typeService.updateType(id, type);
System.out.println("type2:"+type2);
if(type2!=null){
attributes.addFlashAttribute("message","更新成功");
} else {
attributes.addFlashAttribute("message","更新失败");
}
return "redirect:/admin/types";
}