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测试

相关推荐
2301_7930698219 分钟前
前后端分离下,Spring Boot 请求从发起到响应的完整执行流程
java·spring boot·mvc
褚瑱琅22 分钟前
T-SQL语言的压力测试
开发语言·后端·golang
东方靖岚3 小时前
R语言的数据库交互
开发语言·后端·golang
武昌库里写JAVA5 小时前
SpringCloud
vue.js·spring boot·毕业设计·layui·课程设计
uhakadotcom5 小时前
Python 量化计算入门:基础库和实用案例
后端·算法·面试
小萌新上大分5 小时前
SpringCloudGateWay
java·开发语言·后端·springcloud·springgateway·cloudalibaba·gateway网关
uhakadotcom6 小时前
使用Python获取Google Trends数据:2025年详细指南
后端·面试·github
uhakadotcom6 小时前
使用 Python 与 Google Cloud Bigtable 进行交互
后端·面试·github
直视太阳6 小时前
springboot+easyexcel实现下载excels模板下拉选择
java·spring boot·后端
24白菜头7 小时前
C和C++(list)的链表初步
c语言·数据结构·c++·笔记·算法·链表