SpringBoot项目实现分类管理与标签管理

1、分类管理

①、创建typeDAO接口继承自JpaRepository<Type,long>,定义通过标签名字查找的方法头

public interface TypeRepository extends JpaRepository<Type,Long> {
    Type findByName(String name);
}

②、在类别服务接口中添加用于保存、获取、添加、删除、更新type的方法头

    Type saveType(Type type);
    Type getTypeByName(String name);
    void delete(Long id);
    Type getType(Long id);
    Type updateType(Long id,Type type);

③、在TypeServiceImpl中实现这些接口方法,除更新之外的操作只需要直接调用TypeRepository中自带的方法即可,更新操作添加一步对更新的类别是否存在的判断

    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);
    }

④、在TypeController类中实现这些方法的前后端对接,以添加功能为例

    @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";
    }

2、标签管理

①、创建标签Tag实体,具有Id与Name两个属性

②、创建标签DAO接口继承自JpaRepository<Tag,Long>,定义通过标签名字查找的方法头

public interface TagRepository extends JpaRepository<Tag,Long> {
    Tag findByName(String name);
}

③、在标签服务接口中添加用于保存、获取、添加、删除、更新type的方法头

    Page<Tag> listTag(Pageable pageable);
    Tag saveTag(Tag tag);
    Tag getTagByName(String name);
    void deleteTag(Long id);
    Tag getTag(Long id);
    Tag updateTag(Long id, Tag tag);

④、在TagServiceImpl中实现这些接口方法,实现方法逻辑与TypeServiceImpl中相同

⑤、在TagController类中实现这些方法的前后端对接,实现方法逻辑与TypeController中相同

posted @ 2020-07-28 16:49  Dragon_xl  阅读(747)  评论(0)    收藏  举报