看一下新增文章的需求:
接口文檔:
開發思路:
先在controller下去創建add方法,方法內導入Service類獲取add的結果;再在Service接口下去創建add的方法;然后在Service實現類下去實現方法的作用,且導入Mapper類去執行要對數據庫執行的操作。
實操:
1.controller
先創建在controller包下去創建屬于分類的controller類
package org.huangyingyuan.controller;import org.huangyingyuan.pojo.Category;
import org.huangyingyuan.pojo.Result;
import org.huangyingyuan.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
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 {@Autowiredprivate CategoryService categoryService;@PostMapping("/add")public Result add(@RequestBody Category category) {categoryService.add(category);return Result.success();}
}
2.Service接口
package org.huangyingyuan.service;import org.huangyingyuan.pojo.Category;
import org.springframework.stereotype.Service;@Service
public interface CategoryService {// 新增分類void add(Category category);
}
3.ServiceImpl
package org.huangyingyuan.service.impl;import org.huangyingyuan.mapper.CategoryMapper;
import org.huangyingyuan.pojo.Category;
import org.huangyingyuan.service.CategoryService;
import org.huangyingyuan.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 CategoryServiceIpml implements CategoryService {@Autowiredprivate CategoryMapper categoryMapper;@Overridepublic void add(Category category) {//新增屬性值category.setCreate_time(LocalDateTime.now());category.setUpdate_time(LocalDateTime.now());//獲取idMap<String,Object> map=ThreadLocalUtil.get();Integer id=(Integer)map.get("id");category.setCreate_user(id);categoryMapper.add(category);}
}
4.Mapper
package org.huangyingyuan.mapper;import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.huangyingyuan.pojo.Category;@Mapper
public interface CategoryMapper {@Insert("insert into category (category_name,category_alias,create_user,create_time,update_time)" +" values (#{category_name},#{category_alias},#{create_user},#{create_time},#{update_time})")void add(Category category);
}
結果如下:
測試:
成功結果:
參數校驗
我們前面是開發完了,但是一些參數條件沒有制約,現在我們來看一下
那么我們只需要這么兩步操作:
?
在pojo實體類下去接入注解:
然后在controller引入的參數時去加入【@Validated】注解