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

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

目录

发布文章

接口文档

 业务实现

自定义参数校验

项目参数要求 

实现思路 

实现步骤

文章列表(条件分页)

接口文档 

业务实现 

mapper映射 

更新文章

 接口文档

 业务实现

获取文章详情 

接口文档 

业务实现 

删除文章 

接口文档 

业务实现 


文章管理业务表结构

发布文章

接口文档

 业务实现

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

@RestController
@RequestMapping("/article")
public class ArticleController {@Autowiredprivate ArticleService articleService; //注入ArticleService接口@PostMappingpublic 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 {@Autowiredprivate ArticleMapper articleMapper; //注入ArticleMapper接口@Overridepublic 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则校验通过*/@Overridepublic 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中的请求的方法

    @GetMappingpublic 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接口实现类的方法

    @Overridepublic PageBean<Article> list(Integer pageNum, Integer pageSize, String categoryId, String state) {//定义pageBean对象PageBean<Article> pb = new PageBean<>();//开启分页查询 PageHelperPageHelper.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 mapperPUBLIC "-//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中的请求的方法

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

编写ArticleService接口的方法

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

编写ArticleServiceimpl接口实现类的方法

    @Overridepublic 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接口实现类的方法

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

编写ArticleMapper接口的方法

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

 运行请求查看

删除文章 

接口文档 

业务实现 

编写ArticleController中的请求的方法

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

编写ArticleService接口的方法

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

编写ArticleServiceimpl接口实现类的方法

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

编写ArticleMapper接口的方法

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

运行请求查看

 

 

http://www.lryc.cn/news/348130.html

相关文章:

  • 【面试八股总结】C++11新特性:智能指针
  • 【教程向】从零开始创建浏览器插件(二)深入理解 Chrome 扩展的 manifest.json 配置文件
  • 美易官方:美国房地产贷款逾期率飙升,银行业危机仍可控?现货黄金暂守2360
  • SwiftUI中的@StateObject和@ObservedObject的区别
  • 类与对象(二)
  • LeetCode/NowCoder-链表经典算法OJ练习2
  • 英伟达解码性能NVDEC
  • 文心一言 VS 讯飞星火 VS chatgpt (255)-- 算法导论18.3 1题
  • C++ | Leetcode C++题解之第73题矩阵置零
  • 用 Supabase CLI 进行本地开发环境搭建
  • 三极管 导通条件
  • 一次pytorch分布式训练精度调试过程
  • STM32(GPIO)
  • python设计模式---观察者模式
  • 【论文笔记】KAN: Kolmogorov-Arnold Networks 全新神经网络架构KAN,MLP的潜在替代者
  • 【投稿资讯】区块链会议CCF C -- CoopIS 2024 截止7.10 附录用率
  • React Native 之 开发环境搭建(一)
  • DS高阶:B树系列
  • 第五百零三回
  • [动态规划] 完美覆盖
  • redis深入理解之实战
  • python设计模式---工厂模式
  • 探索Vue 3.0中的v-html指令
  • anaconda 环境配置
  • DS:顺序表、单链表的相关OJ题训练(2)
  • 上传到 PyPI
  • 盛最多水的容器(双指针)
  • 【深度学习】实验3 特征处理
  • MoneyPrinter国内版改造
  • C++ 派生类的引入与特性