Spring Boot 笔记 017 创建接口_新增文章

1.1实体类增加校验注释

1.1.1 自定义校验

1.1.1.1 自定义注解

java 复制代码
package com.geji.anno;

import com.geji.validation.StateValidation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import jakarta.validation.constraints.NotEmpty;

import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented//元注解,标识这个注解可以放到帮助文档里面
@Target({ FIELD})//元注解,标志这个注解可以用在哪些地方
@Retention(RUNTIME)//元注解,在哪个阶段被保留,编译,运行等
@Constraint(validatedBy = { StateValidation.class})//指定提供校验规则的类
public @interface State {
    //提供校验失败后的提示信息
    String message() default "state参数的值只能是已发布或者草稿";
    //指定分组
    Class<?>[] groups() default { };
    //负载  获取到State注解的附加信息
    Class<? extends Payload>[] payload() default { };
}

1.1.1.2 自定义校验类

java 复制代码
package com.geji.validation;

import com.geji.anno.State;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

public class StateValidation implements ConstraintValidator<State,String> {
    /**
     *
     * @param value 将来要校验的数据
     * @param context context in which the constraint is evaluated
     *
     * @return 如果返回false,则校验不通过,如果返回true,则校验通过
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        //提供校验规则
        if (value == null){
            return false;
        }
        if (value.equals("已发布") || value.equals("草稿")){
            return true;
        }
        return false;
    }
}

1.1.1.3 在需要的地方使用注解

java 复制代码
package com.geji.pojo;


import com.geji.anno.State;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import java.time.LocalDateTime;

@Data
public class Article {
    private Integer id;//主键ID
    @NotEmpty
    @Pattern(regexp = "^\\S{1,10}$")
    private String title;//文章标题
    @NotEmpty
    private String content;//文章内容
    @NotEmpty
    @URL
    private String coverImg;//封面图像

    @State
    private String state;//发布状态 已发布|草稿
    @NotNull
    private Integer categoryId;//文章分类id
    private Integer createUser;//创建人ID
    private LocalDateTime createTime;//创建时间
    private LocalDateTime updateTime;//更新时间
}

1.1 Controller

java 复制代码
package com.geji.controller;

import com.geji.pojo.Article;
import com.geji.pojo.Result;
import com.geji.service.ArticleService;
import com.geji.utils.JwtUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        articleService.add(article);
        return Result.success();
    }
}

1.2 Service

java 复制代码
package com.geji.service;

import com.geji.pojo.Article;

public interface ArticleService {
    void add(Article article);
}

1.3 ServiceImpl

java 复制代码
package com.geji.service.impl;

import com.geji.mapper.ArticleMapper;
import com.geji.pojo.Article;
import com.geji.service.ArticleService;
import com.geji.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 ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        //补充属性值
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);

        articleMapper.add(article);
    }
}

1.4 Mapper

java 复制代码
package com.geji.mapper;


import com.geji.pojo.Article;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface ArticleMapper {
    //新增
    @Insert("insert into article(title,content,cover_img,state,category_id,create_user,create_time,update_time) " +
            "values(#{title},#{content},#{coverImg},#{state},#{categoryId},#{createUser},#{createTime},#{updateTime})")
    void add(Article article);

}

1.5 Postman测试

相关推荐
逑之7 分钟前
C语言笔记16:文件操作
c语言·笔记·单片机
小杨同学498 分钟前
C 语言贪心算法实战:解决经典活动选择问题
后端
+VX:Fegn08958 分钟前
计算机毕业设计|基于springboot + vue物流配送中心信息化管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·小程序·课程设计
wdfk_prog20 分钟前
[Linux]学习笔记系列 -- 底层CPU与体系结构宏
linux·笔记·学习
计算机毕设指导621 分钟前
基于微信小程序的钓鱼论坛系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
qq_124987075322 分钟前
基于微信小程序的宠物交易平台的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·微信小程序·小程序·毕业设计·计算机毕业设计
内存不泄露23 分钟前
基于Spring Boot和Vue的企业办公自动化系统设计与实现
java·vue.js·spring boot·intellij-idea
禹曦a24 分钟前
Java实战:Spring Boot 构建电商订单管理系统RESTful API
java·开发语言·spring boot·后端·restful
逑之24 分钟前
C语言笔记15:动态内存管理
c语言·网络·笔记
code_lfh24 分钟前
Spring Boot测试类的使用参考
java·spring boot·junit