springboot3项目练习详细步骤(第三部分:文章管理模块)

目录

发布文章

接口文档

 业务实现

自定义参数校验

项目参数要求 

实现思路 

实现步骤

文章列表(条件分页)

接口文档 

业务实现 

mapper映射 

更新文章

 接口文档

 业务实现

获取文章详情 

接口文档 

业务实现 

删除文章 

接口文档 

业务实现 


文章管理业务表结构

发布文章

接口文档

 业务实现

创建ArticleController类并完成请求的方法

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

    @Autowired
    private ArticleService articleService; //注入ArticleService接口

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

创建ArticleService接口并完成方法

public interface ArticleService {
    //新增文章
    void add(Article article);
}

创建ArticleServiceimpl接口实现类并完成方法

@Service
public class ArticleServiceimpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper; //注入ArticleMapper接口
    @Override
    public void add(Article article) {
        //补充id属性值 用于添加到create_usera字段中
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateUser(id);

        articleMapper.add(article);
    }
}

创建ArticleMapper接口并完成方法

@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},now(),now())")
    void add(Article article);
}

运行请求查看 

 数据库中查看已添加成功

自定义参数校验

    已有的注解不能满足所有的校验需求,特殊的情况需要自定义校验(自定义校验注解) 

项目参数要求 

实现思路 

  1. 自定义注解State
  2. 自定义校验数据的类StateValidation 实现ConstraintValidator接口
  3. 在需要校验的地方使用自定义注解 

 实现步骤

 在Article实体类中对能满足校验要求的成员变量进行校验

在ArticleController接口中对方法参数使用@Validated注解 

但对于state变量参数已有的注解不能满足所有的校验需求,所以需要对其使用自定义参数校验。

新建anno包,在包下新定义State注解,并完善定义注解的代码

@Documented //元注解 用于抽取自定义的注解到帮助文档
@Target({ElementType.FIELD}) //元注解 自定义的标注用在哪些地方 FIELD表示在变量属性上标注
@Retention(RetentionPolicy.RUNTIME) //元注解 用于标识自定义的注解会在哪一阶段保留 RUNTIME表示运行阶段
@Constraint(validatedBy = {}) //用于指定谁给自定义的注解定义参数校验规则
public @interface State {

    //message用于提供校验失败后的提示信息
    String message() default "'state参数的值只能是已发布或者草稿";

    //用于指定分组
    Class<?>[] groups() default {};

    //负载 获取到State注解的附如信息
    Class<? extends Payload>[] payload() default {};
}

新建validation包,在包下定义StateValidation校验规则类,并完善校验规则代码

public class StateValidation implements ConstraintValidator<State,String> { //接口的泛型:<会给哪个注解提供校验规则,校验的数据类型>

    /**
     *参数解释:
     *
     * value:将来要校验的数据
     * context
     * 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; //其余情况返回false
    }
}

 再回到State注解中完善要指定的校验规则

到实体类中在需要的成员变量使用该自定义注解用于达到注解参数校验的目的

文章列表(条件分页)

接口文档 

业务实现 

创建PageBean实体类 

//分页返回结果对象
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageBean <T>{
    private Long total;//总条数
    private List<T> items;//当前页数据集合
}

编写ArticleController中的请求的方法

    @GetMapping
    public Result<PageBean<Article>> list(Integer pageNum,
                                          Integer pageSize,  //使用@RequestParam(required = false)可以使参数设置为可传入也可不传入
                                          @RequestParam(required = false) String categoryId,
                                          @RequestParam(required = false) String state){

        PageBean<Article> pb = articleService.list(pageNum,pageSize,categoryId,state);
        return Result.success(pb);
    }

编写ArticleService接口的方法

    //条件分页列表查询
    PageBean<Article> list(Integer pageNum, Integer pageSize, String categoryId, String state);
}

在pom文件导入pagehelper插件依赖用于完成分页查询 

        <!-- pagehelper插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.6</version>
        </dependency>

编写ArticleServiceimpl接口实现类的方法

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, String categoryId, String state) {
        //定义pageBean对象
        PageBean<Article> pb = new PageBean<>();

        //开启分页查询 PageHelper
        PageHelper.startPage(pageNum,pageSize);

        //添加id参数 调用mapper接口的方法
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        List<Article> arlist = articleMapper.list(id,categoryId,state);
        //page中提供了方法可以获取pagehelper分页查询后,得到的总记录条数和当前页数
        Page<Article> p = (Page<Article>) arlist;

        //将page对象获取的记录和条数添加到pagebean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());

        return  pb; //返回pagebean对象
    }

编写ArticleMapper接口的方法 

    //条件分页列表查询
    List<Article> list(Integer id, String categoryId, String state);

mapper映射 

由于参数 categoryId和state参数为非必填,所以这里sql需要用到sql映射文件来写动态sql

在resource目录下创建和mapper包一样的结构目录

目录结构要和mapper接口目录相同

配置文件名称要和接口名称相同

编写sql映射配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 命名空间要和mapper接口的路径全类名要相同   -->
<mapper namespace="com.springboot.springboot_test.mapper.ArticleMapper">
<!-- 编写动态sql
select标签的
id参数要和mapper接口的方法名称一致
resultType 返回值类型要和实体类名称一致-->
    <select id="list" resultType="com.springboot.springboot_test.pojo.Article">
        select * from article
        <where>
            <if test="categoryId != null">
                category_id = #{categoryId}
            </if>

            <if test="state != null">
                and state = #{state}
            </if>

            and create_user= #{id}
        </where>
    </select>
    
</mapper>

运行请求查看

 

更新文章

 接口文档

 业务实现

编写ArticleController中的请求的方法

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

编写ArticleService接口的方法

    //更新文章
    void update(Article article);

编写ArticleServiceimpl接口实现类的方法

    @Override
    public void update(Article article) {
        articleMapper.update(article);
    }

编写ArticleMapper接口的方法

    //更新文章
    @Update("update article set title = #{title},content = #{content},cover_img = #{coverImg},state = #{state}, " +
            "category_id = #{categoryId},update_time = now() where id = #{id}")
    void update(Article article);

运行请求查看

 

获取文章详情 

接口文档 

业务实现 

编写ArticleController中的请求的方法

    @GetMapping("/detail")
    public Result detail(Integer id){
        Article ar = articleService.findById(id);

        return Result.success(ar);
    }

编写ArticleService接口的方法

    //查看文章详情
    Article findById(Integer id);

编写ArticleServiceimpl接口实现类的方法

    @Override
    public Article findById(Integer id) {
        Article ar = articleMapper.findById(id);
        return ar;
    }

编写ArticleMapper接口的方法

    //查看文章详情
    @Select("select * from article where id =#{id}")
    Article findById(Integer id);

 运行请求查看

删除文章 

接口文档 

业务实现 

编写ArticleController中的请求的方法

    @DeleteMapping
    public Result delete(Integer id){
        articleService.delete(id);
        return Result.success();
    }

编写ArticleService接口的方法

    //删除文章
    void delete(Integer id);

编写ArticleServiceimpl接口实现类的方法

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }

编写ArticleMapper接口的方法

    //删除文章
    @Delete("delete from article where id = #{id}")
    void delete(Integer id);

运行请求查看

 

 

  • 22
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

open_test01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值