Spring Boot + vue-element 开发个人博客项目实战教程(十四、文章功能实现(上))2

简介: Spring Boot + vue-element 开发个人博客项目实战教程(十四、文章功能实现(上))2

3.5、对象查询

这里我再提一下,在我们根据id查找对象的时候,我先去缓存中就查找,如果缓存中没有再去数据库中查找。

拿map的key去查找。

    @Override
    public Article findById(Integer articleId) {
        Article article = articleMap.get(articleId);
        if (article == null) {
            Article art = articleMapper.getById(articleId);
            return art;
        }
        return article;
    }

实现类完整代码:TagServiceImpl.java

package com.blog.personalblog.service.Impl;
import com.blog.personalblog.bo.ArticleBO;
import com.blog.personalblog.entity.Article;
import com.blog.personalblog.mapper.ArticleMapper;
import com.blog.personalblog.service.ArticleService;
import com.github.pagehelper.PageHelper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
 * @author: SuperMan
 * @create: 2021-12-01
 */
@Log4j2
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    /**
     * key:文章id
     * value: 文章
     */
    Map<Integer, Article> articleMap = new LinkedHashMap<>();
    @Override
    @PostConstruct
    public void init() {
        List<Article> articleList = articleMapper.findAll();
        try {
            for(Article article : articleList) {
                articleMap.put(article.getId(), article);
            }
            log.info("文章缓存数据加载完成");
        } catch (Exception e) {
            log.error("文章缓存数据加载失败!", e.getMessage());
        }
    }
    @Override
    public List<Article> getArticlePage(ArticleBO articleBO) {
        int pageNum = articleBO.getPageNum();
        int pageSize = articleBO.getPageSize();
        PageHelper.startPage(pageNum,pageSize);
        List<Article> articleList = articleMapper.getArticlePage(articleBO);
        return articleList;
    }
    @Override
    public void saveArticle(Article article) {
        articleMapper.createArticle(article);
        articleMap.put(article.getId(), article);
    }
    @Override
    public void updateArticle(Article article) {
        articleMapper.updateArticle(article);
        articleMap.put(article.getId(), article);
    }
    @Override
    public void deleteArticle(Integer articleId) {
        articleMapper.deleteArticle(articleId);
        articleMap.remove(articleId);
    }
    @Override
    public Article findById(Integer articleId) {
        Article article = articleMap.get(articleId);
        if (article == null) {
            Article art = articleMapper.getById(articleId);
            return art;
        }
        return article;
    }
}

4、数据库查询接口实现

新建ArticleMapper.java接口:

这个没有什么好讲的和以前几乎一样,我就直接展示代码了

package com.blog.personalblog.mapper;
import com.blog.personalblog.bo.ArticleBO;
import com.blog.personalblog.entity.Article;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * @author: SuperMan
 * @create: 2021-12-01
 */
@Repository
public interface ArticleMapper {
    /**
     * 查询所有的文章列表
     * @return
     */
    List<Article> findAll();
    /**
     * 创建文章
     * @param article
     * @return
     */
    int createArticle(Article article);
    /**
     * 修改文章
     * @param article
     * @return
     */
    int updateArticle(Article article);
    /**
     * 分类列表(分页)
     * @param articleBO
     * @return
     */
    List<Article> getArticlePage(@Param("articleBO") ArticleBO articleBO);
    /**
     * 删除文章
     * @param id
     */
    void deleteArticle(Integer id);
    /**
     * 根据id查找分类
     * @param id
     * @return
     */
    Article getById(Integer id);
}

5、编写数据库xml

这个的重点我在实现类中也已经讲过了,其余的都是正常的增删改的sql语句了。

新建一个ArticleMapper.xml文件

<?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 namespace="com.blog.personalblog.mapper.ArticleMapper">
    <resultMap id="BaseResultMap" type="com.blog.personalblog.entity.Article">
        <result column="id" jdbcType="INTEGER" property="id"/>
        <result column="author" jdbcType="VARCHAR" property="author"/>
        <result column="title" jdbcType="VARCHAR" property="title"/>
        <result column="user_id" jdbcType="INTEGER" property="userId"/>
        <result column="category_id" jdbcType="INTEGER" property="categoryId"/>
        <result column="content" jdbcType="VARCHAR" property="content"/>
        <result column="views" jdbcType="BIGINT" property="views"/>
        <result column="total_words" jdbcType="BIGINT" property="totalWords"/>
        <result column="commentable_id" jdbcType="INTEGER" property="commentableId"/>
        <result column="art_status" jdbcType="INTEGER" property="artStatus"/>
        <result column="description" jdbcType="VARCHAR" property="description"/>
        <result column="image_url" jdbcType="VARCHAR" property="imageUrl"/>
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
        <result column="categoryname" jdbcType="VARCHAR" property="categoryName"></result>
        <collection property="tagList" ofType="com.blog.personalblog.entity.Tag">
            <id column="sid" property="id"/>
            <result column="tag_name" property="tagName"/>
            <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
            <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
        </collection>
    </resultMap>
    <sql id="Base_Column_List">
        id, author, title, user_id, category_id, content, views, total_words, commentable_id,
        art_status, description, image_url, create_time, update_time
    </sql>
    <select id="findAll" resultMap="BaseResultMap">
       select
        <include refid="Base_Column_List"/>
       from person_article
    </select>
    <select id="getArticlePage" resultMap="BaseResultMap" parameterType="com.blog.personalblog.bo.ArticleBO">
        SELECT
        a.*,
        tag.article_id,
        tag.tag_id,
        s.id AS sid,
        u.category_name categoryname,
        s.tag_name
        FROM person_article a
        left join person_category u on a.category_id = u.category_id
        left join person_article_tag tag on a.id = tag.article_id
        left join person_tag s on s.id = tag.tag_id
        <where>
            <if test="articleBO.title != null">
                and a.title like '%${articleBO.title}%'
            </if>
            <if test="articleBO.categoryId != null">
                and a.category_id = #{articleBO.categoryId}
            </if>
            <if test="articleBO.artStatus != null">
                and a.art_status = #{articleBO.artStatus}
            </if>
        </where>
    </select>
    <insert id="createArticle" parameterType="com.blog.personalblog.entity.Article" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO person_article
            (author, title, user_id, category_id, content, views, total_words,
             commentable_id, art_status, description, image_url)
        VALUES(#{author}, #{title}, #{userId}, #{categoryId}, #{content}, #{views}, #{totalWords}, #{commentableId},
               #{artStatus}, #{description}, #{imageUrl})
    </insert>
    <update id="updateArticle" parameterType="com.blog.personalblog.entity.Tag">
        update person_article
        <set>
            author = #{author},
            title = #{title},
            user_id = #{userId},
            category_id = #{categoryId},
            views = #{views},
            total_words = #{totalWords},
            commentable_id = #{commentableId},
            art_status = #{artStatus},
            description = #{description},
            image_url = #{imageUrl}
        </set>
        WHERE id = #{id}
    </update>
    <delete id="deleteArticle" parameterType="java.lang.Integer">
        delete from person_article where id = #{id, jdbcType=INTEGER}
    </delete>
    <select id="getById" resultType="com.blog.personalblog.entity.Article">
        select * from person_article
        where id = #{id}
    </select>
</mapper>

6、编写接口层

新建一个文章的接口类:ArticleController.java

package com.blog.personalblog.controller;
import com.blog.personalblog.bo.ArticleBO;
import com.blog.personalblog.config.page.PageRequest;
import com.blog.personalblog.config.page.PageResult;
import com.blog.personalblog.entity.Article;
import com.blog.personalblog.service.ArticleService;
import com.blog.personalblog.util.JsonResult;
import com.blog.personalblog.util.PageUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
 * @author: SuperMan
 * @create: 2021-12-01
 */
@Api(tags = "文章管理")
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;
    /**
     * 文章列表
     * @param articleBO
     * @return
     */
    @ApiOperation(value = "文章列表")
    @PostMapping("list")
    public JsonResult<Object> listPage(@RequestBody @Valid ArticleBO articleBO) {
        List<Article> articleList = articleService.getArticlePage(articleBO);
        PageInfo pageInfo = new PageInfo(articleList);
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPageNum(articleBO.getPageNum());
        pageRequest.setPageSize(articleBO.getPageSize());
        PageResult pageResult = PageUtil.getPageResult(pageRequest, pageInfo);
        return JsonResult.success(pageResult);
    }
    /**
     * 添加文章
     * @return
     */
    @ApiOperation(value = "添加文章")
    @PostMapping("/create")
    public JsonResult<Object> articleCreate(@RequestBody @Valid Article article) {
        articleService.saveArticle(article);
        return JsonResult.success();
    }
    /**
     * 修改文章
     * @return
     */
    @ApiOperation(value = "修改文章")
    @PostMapping("/update")
    public JsonResult<Object> articleUpdate(@RequestBody @Valid Article article) {
        articleService.updateArticle(article);
        return JsonResult.success();
    }
    /**
     * 删除文章
     * @return
     */
    @ApiOperation(value = "删除文章")
    @DeleteMapping("/delete/{id}")
    public JsonResult<Object> articleDelete(@PathVariable(value = "id") int id) {
        articleService.deleteArticle(id);
        return JsonResult.success();
    }
    /**
     * 根据文章id查找
     * @param id
     * @return
     */
    @ApiOperation(value = "根据文章id查找")
    @PostMapping("/getArticle/{id}")
    public JsonResult<Object> getArticleById(@PathVariable(value = "id") int id) {
        Article article = articleService.findById(id);
        return JsonResult.success(article);
    }
}

以上的功能都是文章基本的东西,后面我们还会修改和添加功能,具体的会在第二篇进行补充和完善。

二、测试

接下来启动我们的项目,我们测试一下我们的接口,先能保证接口都是通的,才能进行下一步的操作。

1、添加文章接口测试

打开PostMan,我们新建一个文章管理的文件夹,当然你也可以选择在Swagger接口中进行测试,我们这里用Postman进行测试。

我们将添加的参数以JSON的格式进行传参。

打开数据库,查看有没有添加成功

2、修改文章接口测试

修改接口基本上和添加的参数一致,就是比添加多了一个文章id,我们要修改那一篇文章要告诉后台的服务,才能进行相关的修改。

再新建 一个修改文章的接口。再看一下数据库有没有修改

3、删除文章接口测试

删除的很简单,就是要删除哪一篇文章传入个id就可以了。

我们这里使用@DeleteMapping请求方式看一下数据库中的数据已经成功的删除了

4、查询接口测试

查询的接口我们会有参数进行查询的,同时还带有分页查询。

这个查询牵连的表比较多,我们要确保分类表和标签表里有值,然后还要在关联表中手动添加一些值,方便我们进行测试。(2)标签表:(3)文章表:我就以这个为例了,分类设置的为1(4)然后看关联表:

大家可以看到关联表中我一共放了两个值,文章id为1的有两个标签,由于我们关联表功能还没和文章连接,我们自己先搞点值测一测接口。这里说明文章有两个标签,就说明我们在查找出来的文章中会有两个标签进行展示。
新建一个请求接口:

我们先测试以下什么参数都不传,将所有的数据都查询出来。
看下返回的数据,标签确实有两条数据,说明我们写的没有问题。然后下面再多添加几条数据,进行参数的测试。我们查询title标题的模糊查询,看是否能查出来。

看确实查询出来了,而且只查出来这一条符合条件的,说明我们的条件查询也是对的,还有剩下的两个参数大家自己测一测吧,我就不一一列举了。
好啦!这一篇文章写了很长时间,搞了一个元旦,新的一年大家努力啊!麻烦大家给点个赞吧。

在这里我收集下大家的反馈!

目录
相关文章
|
18小时前
|
JavaScript 前端开发 Java
基于SpringBoot+Vue实现前后端交互功能(详解Vue框架机制)
基于SpringBoot+Vue实现前后端交互功能(详解Vue框架机制)
|
18小时前
|
前端开发 Java 数据库连接
Spring系列文章1:Spring入门程序
Spring系列文章1:Spring入门程序
|
18小时前
|
开发框架 监控 Java
深入探索Spring Boot的监控、管理和测试功能及实战应用
【5月更文挑战第14天】Spring Boot是一个快速开发框架,提供了一系列的功能模块,包括监控、管理和测试等。本文将深入探讨Spring Boot中监控、管理和测试功能的原理与应用,并提供实际应用场景的示例。
14 2
|
18小时前
|
Java 关系型数据库 MySQL
保姆级教程——将springboot项目部署到阿里云服务器包含环境配置(小白包会)
本文档详细介绍了将SpringBoot项目部署到阿里云服务器的步骤。首先,通过Xshell连接服务器,使用公网IP地址。接着,下载JDK的Linux版本,使用XFTP上传并解压,配置环境变量。然后,安装MySQL 5.7,包括下载YUM源、安装、启动服务以及修改root密码和开启远程访问。最后,将SpringBoot项目打包成jar,上传至服务器,使用`java -jar`命令运行,通过`nohup`确保服务持续运行。配置安全组以允许远程访问。
|
18小时前
|
传感器 人工智能 前端开发
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
智慧校园电子班牌,坐落于班级的门口,适合于各类型学校的场景应用,班级学校日常内容更新可由班级自行管理,也可由学校统一管理。让我们一起看看,电子班牌有哪些功能呢?
101 4
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
|
18小时前
|
Java 数据库连接 数据库
Springboot整合mybatisPlus开发
MyBatis-Plus是一个MyBatis的增强工具,旨在简化开发和提高效率。它在不修改原有MyBatis的基础上提供额外功能。要将MyBatis-Plus集成到SpringBoot项目中,首先通过Maven添加mybatis-plus-boot-starter和相应数据库驱动依赖,然后配置application.yml中的数据库连接信息,并指定Mapper类的扫描路径。Mapper接口可继承BaseMapper实现基本的CRUD操作。
|
18小时前
|
前端开发 JavaScript Java
Springboot框架整合jsp开发【干货满满】
该文介绍了如何在Spring Boot中集成JSP,需包含`spring-boot-starter-web`、`tomcat-embed-jasper`和`jstl`三个依赖。配置Spring Boot寻找JSP的位置,设置`spring.mvc.view.prefix`为`/WEB-INF/jsp/`,`spring.mvc.view.suffix`为`.jsp`。JSP文件应放在`src/main/webapp/WEB-INF/jsp/`下。
|
18小时前
|
Web App开发 前端开发 Java
SpringBoot配置HTTPS及开发调试
在实际开发过程中,如果后端需要启用https访问,通常项目启动后配置nginx代理再配置https,前端调用时高版本的chrome还会因为证书未信任导致调用失败,通过摸索整理一套开发调试下的https方案,特此分享
21 0
SpringBoot配置HTTPS及开发调试
|
18小时前
|
IDE Java 开发工具
Spring Boot DevTools:加速开发的热部署工具
【4月更文挑战第28天】在Spring Boot的开发过程中,快速反馈和效率至关重要。Spring Boot DevTools是一个为开发者设计的模块,支持热部署(hot swapping),能够实现应用的快速重启和自动重载,极大地提高了开发效率。本篇博客将介绍Spring Boot DevTools的核心概念,并通过具体的实战示例展示如何在开发过程中利用这一工具。
24 0
|
18小时前
|
Java Maven Kotlin
[AIGC] 请你写一遍博客介绍 “使用idea+kotinlin+springboot+maven 结合开发一个简单的接口“,输出markdown格式,用中文回答,请尽可能详细
[AIGC] 请你写一遍博客介绍 “使用idea+kotinlin+springboot+maven 结合开发一个简单的接口“,输出markdown格式,用中文回答,请尽可能详细