当前位置: 首页 > news >正文

SpringBoot速成(12)文章分类P15-P19

1.新增文章分类

1.Postman登录不上,可以从头registe->login一个新的成员:注意,跳转多个url时,post/get/patch记得修改成controller类中对应方法上写的

2.postman运行成功:

但表中不更新:细节有问题:

c是小写

拼写错误

3.sql层报错,已运行到mapper层->controller层没有对参数校验

参数校验:

1.pojo层

2.controller层

运行后 :

代码展示:

pojo:

package com.itheima.springbootconfigfile.pojo;

import jakarta.validation.constraints.NotEmpty;
import lombok.Data;

import java.time.LocalDateTime;
@Data
public class Category {
    private Integer id;//主键ID
    @NotEmpty
    private String categoryName;//分类名称
    @NotEmpty
    private String categoryAlias;//分类别名
    private Integer createUser;//创建人ID
    private LocalDateTime createTime;//创建时间
    private LocalDateTime updateTime;//更新时间

    @Override
    public String toString() {
        return "Category{" +
                "id=" + id +
                ", categoryName='" + categoryName + '\'' +
                ", categoryAlias='" + categoryAlias + '\'' +
                ", createUser=" + createUser +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                '}';
    }

    public Category() {
    }

    public Category(Integer id, String categoryName, String categoryAlias, Integer createUser, LocalDateTime createTime, LocalDateTime updateTime) {
        this.id = id;
        this.categoryName = categoryName;
        this.categoryAlias = categoryAlias;
        this.createUser = createUser;
        this.createTime = createTime;
        this.updateTime = updateTime;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getCategoryAlias() {
        return categoryAlias;
    }

    public void setCategoryAlias(String categoryAlias) {
        this.categoryAlias = categoryAlias;
    }

    public Integer getCreateUser() {
        return createUser;
    }

    public void setCreateUser(Integer createUser) {
        this.createUser = createUser;
    }

    public LocalDateTime getCreateTime() {
        return createTime;
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
    }

    public LocalDateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(LocalDateTime updateTime) {
        this.updateTime = updateTime;
    }
}

controller:

package com.itheima.springbootconfigfile.controller;

import com.itheima.springbootconfigfile.pojo.Category;
import com.itheima.springbootconfigfile.pojo.Result;
import com.itheima.springbootconfigfile.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("/add")
    public Result add(@RequestBody @Validated Category category){
        categoryService.add(category);
        return  Result.success();
    }

}

categoryServiceIMpl:

package com.itheima.springbootconfigfile.service.impl;

import com.itheima.springbootconfigfile.mapper.CategoryMapper;
import com.itheima.springbootconfigfile.pojo.Category;
import com.itheima.springbootconfigfile.service.CategoryService;
import com.itheima.springbootconfigfile.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);//连接user表中的id,即userId=createUser=id
            categoryMapper.add(category);

    }
}

categoryMapper:

package com.itheima.springbootconfigfile.mapper;

import com.itheima.springbootconfigfile.pojo.Category;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface CategoryMapper {
    @Insert("insert into category (categoryName,categoryAlias,createUser,createTime,updateTime) values (#{categoryName},#{categoryAlias},#{createUser},now(),now())")
    void add(Category category);
}


2.文章分类列表(显示当前用户已有的所有文章分类)

代码展示:

controller:

 //文章分类列表
    @GetMapping()
    public  Result<List<Category>> list(){
        List<Category> cs=categoryService.list();
        return Result.success(cs);
    }

categoryServiceImpl:

 @Override
    public List<Category> list() {
        Map<String,Object> map=ThreadLocalUtil.get();
        Integer userId= (Integer) map.get("id");



       return categoryMapper.list(userId);
    }

categoryMapper:

  @Select("select * from category where createUser=#{userId}")
    List<Category> list(Integer userId);

 createUser和userId:

运行:

优化:时间表达不是常规表达

对属性的限制可加在controller类的方法的参数上 或 实体类上

修改:

@Data
public class Category {
    private Integer id;//主键ID
    @NotEmpty
    private String categoryName;//分类名称
    @NotEmpty
    private String categoryAlias;//分类别名
    private Integer createUser;//创建人ID
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;//创建时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;//更新时间

运行:

回忆下User类对属性的注解:

@Data
public class User {
    @NotNull
    private Integer id;//主键ID
    private String username;//用户名
    @JsonIgnore
    //当前对象转变为json字符串时,忽略password,最终的json 字符串就无password这个属性
    private String password;//密码
    @NotEmpty
    @Pattern(regexp = "^\\S{1,10}$")
    private String nickname;//昵称
    @NotEmpty
    @Email
    private String email;//邮箱


3.获取文章分类详情 

代码展示:

controller:

  //获取文章详情
    @GetMapping("/detail")
    public Result<Category> detail(Integer id){

        Category c=categoryService.findById(id);
        return Result.success(c);
    }

categoryServiceImpl:

  @Override
    public Category findById(Integer id) {

       Category c =categoryMapper.findById(id);
       return c;
    }

categoryMapper:

   @Select("select * from category where id=#{id}")
    Category findById(Integer id);

运行: 

可优化:category表和user表是联通的,但该方法没要求必须是本用户才可以查询文章分类详情,即可以查到其他用户的文章分类

但若以文章分类是公共的,也可以不限制


4.更新文章分类 

代码展示:

//更新文章分类
@PutMapping("update")
public Result update(@RequestBody @Validated Category category){
    categoryService.update(category);
    return Result.success();
}
 @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

 @Update("update category set categoryName=#{categoryName},categoryAlias=#{categoryAlias},updateTime=#{updateTime} where id=#{id}")
    void update(Category category);
 @NotNull
    private Integer id;//主键ID

运行:

postman修改后,idea重新运行才会成功

可优化:createUser=userId

思考:

为什么不能这样写:

@PutMapping("update")
public Result<Category> update(Integer id){
    Category c= categoryService.update(id);
    return Result.success(c);
}

 运行报错:

问题的核心在于 CategoryMapper.update 方法的返回类型不被 MyBatis 支持。MyBatis 对于 updatedeleteinsert 等操作的返回类型通常是 int,表示影响的行数,而不是返回一个 POJO 类型。 


5.BUG修改 

bug描述:

第4中在category类增加了

再运行1.add,报错:

修改:分组校验:

定义分组 对校验项分组 指定分组 默认属于什么组

代码展示:

category:

@Data
public class Category {
    @NotNull(groups = Update.class)
    private Integer id;//主键ID
    @NotEmpty(groups = {Add.class,Update.class})
    private String categoryName;//分类名称
    @NotEmpty(groups = {Add.class,Update.class})
    private String categoryAlias;//分类别名
    private Integer createUser;//创建人ID
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;//创建时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;//更新时间


    //分组校验
    //添加组
    public interface Add{

    }
    //更新组
    public interface Update{

    }

categoryController:

//新增文章分类
 @PostMapping("/add")
    public Result add(@RequestBody @Validated(Category.Add.class) Category category){
        categoryService.add(category);
        return  Result.success();
    }









  //更新文章分类
    @PutMapping("update")
    public Result update(@RequestBody @Validated(Category.Update.class) Category category){
        categoryService.update(category);
        return Result.success();
    }

 

运行,成功:

优化:如上面的categoryName,categoryAlias(校验项)在add,update中都有,属于default 或 A类继承B类则A继承B所有校验项

category:id属于update(update时notnull),其他属性属于default

@Data
public class Category {
    @NotNull(groups = Update.class)
    private Integer id;//主键ID
    @NotEmpty
    private String categoryName;//分类名称
    @NotEmpty
    private String categoryAlias;//分类别名
    private Integer createUser;//创建人ID
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;//创建时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;//更新时间


    //分组校验
    //添加组
    public interface Add extends Default {

    }
    //更新组
    public interface Update extends Default{

    }

运行:add()

update()

相关文章:

  • JAVA集合
  • python 视频处理库moviepy 设置字幕
  • 【LeetCode Hot100 矩阵】矩阵置零、螺旋矩阵、旋转图像、搜索二维矩阵II
  • 开源协议深度解析:理解MIT、GPL、Apache等常见许可证
  • JavaScript 简介
  • 枚举类型Enum
  • DeepSeek-R1 + Cherry Studio 本地部署打造个人 AI 知识库
  • C语言01
  • Kimi k1.5:继Deepseek R1 后多模态 AI 的新标杆
  • 低成本、高效率且成熟的电商实时数据采集方案:梦想成真?
  • 放大镜效果
  • 图论算法篇:邻接矩阵以及邻接表和链式前向星建图
  • winfrom实现人脸识别比对功能
  • 大模型开发实战篇5:多模态--文生图模型API
  • 如何设置Python爬虫的User-Agent?
  • torch-xla动态shape——通过torch.nonzero分析mhlo实现
  • 第六天:requests库的用法
  • JS数组扁平化
  • Java与Go相比,有什么独特的优势
  • Openshift或者K8S上部署xxl-job
  • 短剧剧组在贵州拍戏突遇极端天气,演员背部、手臂被冰雹砸伤
  • AI世界的年轻人|“热潮下要有定力”,她的目标是让机器人真正步入家庭
  • 晒被子最大的好处,其实不是杀螨虫,而是……
  • 科普|治疗腰椎间盘突出症,筋骨平衡理论如何提供新视角?
  • 媒体:南京秦淮区卫健委回应一医院涉嫌违规提供试管婴儿服务
  • 马克思主义理论研究教学名师系列访谈|金瑶梅:教师需要了解学生的现实发展,把握其思想发展动态