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

相关推荐
二闹25 分钟前
Python文件读取三巨头你该选择哪一个?
后端·python
彭于晏Yan26 分钟前
Spring AI(二):入门使用
java·spring boot·spring·ai
中屹指纹浏览器41 分钟前
2026指纹浏览器性能瓶颈分析与优化技巧
经验分享·笔记
苏三说技术1 小时前
推荐几个牛逼的AI Agent项目
后端
武子康1 小时前
大数据-253 离线数仓 - Airflow 入门与任务调度实战:DAG、Operator、Executor 部署排错指南
大数据·后端·apache hive
IT_陈寒2 小时前
深入理解JavaScript:核心原理与最佳实践
前端·人工智能·后端
树獭叔叔2 小时前
GRPO:比PPO更简单的RLHF算法
后端·aigc·openai
shelter2 小时前
并发操作session对象导致登录闪退问题
后端
雷工笔记2 小时前
随笔|走!跳楼去!
笔记
兆子龙2 小时前
TypeScript高级类型编程:从入门到精通
前端·后端