1.新增文章分类
文章分类的表结构和实体类

实体类

接口文档

实现
新创建CategoryController,CategoryService,(CategoryServiceImpl),CategoryMapper

在CategoryController中添加方法
使用注解@PostMapping,没有映射路径,我们在CategoryController的类上添加一个映射路径@RequestMapping("/category"),然后同通过请求方式的方式进行区分,来提供服务。
在方法上声明一个实体类参数,加上@RequestBody让MVC框架自动读取请求体中的json数据,并把json数据转换成一个对象。
在mapper层添加分类时,要添加这个分类是谁创建的,创建时间,更新时间。但是接口文档中,前端给我们传递的参数里面只有分类的名称和分类的别名。所以在执行mapper层的sql之前,我们需要在service层中把category里面的一些属性值给它完善好
CategoryController.java
package org.exampletest.controller;
import org.exampletest.pojo.Category;
import org.exampletest.pojo.Result;
import org.exampletest.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @PostMapping
    public Result add(@RequestBody @Validated Category category){
        categoryService.add(category);
        return Result.success();
    }
}
 
CategoryService.java
package org.exampletest.service;
import org.exampletest.pojo.Category;
public interface CategoryService {
    //新增分类
    void add(Category category);
}
 
CategoryServiceImpl.java
package org.exampletest.service.impl;
import org.exampletest.mapper.CategoryMapper;
import org.exampletest.pojo.Category;
import org.exampletest.service.CategoryService;
import org.exampletest.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Map;
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public void add(Category category) {
        //补充属性值
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        Map<String,Object> map= ThreadLocalUtil.get();
        Integer userid = (Integer)map.get("id");
        category.setCreateUser(userid);
        categoryMapper.add(category);
    }
}
 
CategoryMapper.java
package org.exampletest.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.exampletest.pojo.Category;
@Mapper
public interface CategoryMapper {
    //新增分类
    @Insert("insert into category(category_name,category_alias,create_time,update_time)"+"values(#{categoryName},#{categoryAlias},#{createTime},#{updateTime})")
    void add(Category category);
}
 
对参数进行校验
在添加@NotEmpty,@Validated等



















