(仿牛客社区项目)Java开发笔记3.5:添加评论

2023-05-16

文章目录

  • 添加评论
  • 1.dao层
  • 2.service层
  • 3.controller层
  • 4.view层
  • 5.功能测试

添加评论

根据上节的开发安排:显示评论功能完成后,开始实现添加评论功能。

NowCoder_13_1

1.dao层

CommentMapper类中添加insertComment方法。

discuss_post中的comment_count为冗余数据,DiscussPostMapper类中添加updateCommentCount方法。

package com.gerrard.community.dao;

import com.gerrard.community.entity.Comment;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface CommentMapper {

    List<Comment> selectCommentsByEntity(int entityType, int entityId, int offset, int limit);

    int selectCountByEntity(int entityType, int entityId);

    int insertComment(Comment comment);

}

comment-mapper.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.gerrard.community.dao.CommentMapper">

    <sql id="selectFields">
        id, user_id, entity_type, entity_id, target_id, content, status, create_time
    </sql>

    <sql id="insertFields">
        user_id, entity_type, entity_id, target_id, content, status, create_time
    </sql>

    <select id="selectCommentsByEntity" resultType="Comment">
        select <include refid="selectFields"></include>
        from comment
        where status = 0
        and entity_type = #{entityType}
        and entity_id = #{entityId}
        order by create_time asc
        limit #{offset}, #{limit}
    </select>

    <select id="selectCountByEntity" resultType="int">
        select count(id)
        from comment
        where status = 0
        and entity_type = #{entityType}
        and entity_id = #{entityId}
    </select>

    <insert id="insertComment" parameterType="Comment">
        insert into comment(<include refid="insertFields"></include>)
        values(#{userId},#{entityType},#{entityId},#{targetId},#{content},#{status},#{createTime})
    </insert>

</mapper>
package com.gerrard.community.dao;

import com.gerrard.community.entity.DiscussPost;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface DiscussPostMapper {

    List<DiscussPost> selectDiscussPosts(int userId, int offset, int limit);

    // @Param注解用于给参数取别名,
    // 如果只有一个参数,并且在<if>里使用,则必须加别名.
    int selectDiscussPostRows(@Param("userId") int userId);

    int insertDiscussPost(DiscussPost discussPost);

    DiscussPost selectDiscussPostById(int id);

    int updateCommentCount(int id, int commentCount);

}

discusspost-mapper.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.gerrard.community.dao.DiscussPostMapper">

    <sql id="selectFields">
        id, user_id, title, content, type, status, create_time, comment_count, score
    </sql>

    <sql id="insertFields">
        user_id, title, content, type, status, create_time, comment_count, score
    </sql>

    <select id="selectDiscussPosts" resultType="DiscussPost">
        select <include refid="selectFields"></include>
        from discuss_post
        where status != 2
        <if test="userId!=0">
            and user_id = #{userId}
        </if>
        order by type desc, create_time desc
        limit #{offset}, #{limit}
    </select>

    <select id="selectDiscussPostRows" resultType="int">
        select count(id)
        from discuss_post
        where status != 2
        <if test="userId!=0">
            and user_id = #{userId}
        </if>
    </select>

    <insert id="insertDiscussPost" parameterType="DiscussPost">
        insert into discuss_post(<include refid="insertFields"></include>)
        values(#{userId},#{title},#{content},#{type},#{status},#{createTime},#{commentCount},#{score})
    </insert>

    <select id="selectDiscussPostById" resultType="DiscussPost">
        select <include refid="selectFields"></include>
        from discuss_post
        where id = #{id}
    </select>

    <update id="updateCommentCount">
        update discuss_post set comment_count = #{commentCount} where id = #{id}
    </update>

</mapper>

2.service层

CommentService中添加addComment方法(用到事务注解,涉及两张表操作),DiscussPostService中添加updateCommentCount方法。

 package com.gerrard.community.service;

import com.gerrard.community.dao.CommentMapper;
import com.gerrard.community.entity.Comment;
import com.gerrard.community.util.CommunityConstant;
import com.gerrard.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentService implements CommunityConstant {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private DiscussPostService discussPostService;

    public List<Comment> findCommentsByEntity(int entityType, int entityId, int offset, int limit) {
        return commentMapper.selectCommentsByEntity(entityType, entityId, offset, limit);
    }

    public int findCommentCount(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment) {
        if (comment == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);

        // 更新帖子评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            int count = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(), count);
        }

        return rows;
    }

}
package com.gerrard.community.service;

import com.gerrard.community.dao.DiscussPostMapper;
import com.gerrard.community.entity.DiscussPost;
import com.gerrard.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class DiscussPostService {

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit) {
        return discussPostMapper.selectDiscussPosts(userId, offset, limit);
    }

    public int findDiscussPostRows(int userId) {
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    public int addDiscussPost(DiscussPost post) {
        if (post == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 转义HTML标记
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));
        // 过滤敏感词
        post.setTitle(sensitiveFilter.filter(post.getTitle()));
        post.setContent(sensitiveFilter.filter(post.getContent()));

        return discussPostMapper.insertDiscussPost(post);
    }

    public DiscussPost findDiscussPostById(int id) {
        return discussPostMapper.selectDiscussPostById(id);
    }

    public int updateCommentCount(int id, int commentCount) {
        return discussPostMapper.updateCommentCount(id, commentCount);
    }

}

3.controller层

添加CommentController类。

package com.gerrard.community.controller;

import com.gerrard.community.entity.Comment;
import com.gerrard.community.service.CommentService;
import com.gerrard.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;

@Controller
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private HostHolder hostHolder;

    @RequestMapping(path = "/add/{discussPostId}", method = RequestMethod.POST)
    public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment) {
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.addComment(comment);

        return "redirect:/discuss/detail/" + discussPostId;
    }

}

entityId,entityType,【targetId】由前端传入。

用户进行回复,获取comment实体类信息,将comment实体类插入到comment数据库中,再更新discuss_post数据库中comment_count字段(用到事务操作)。

4.view层

有三种回复,一种需要传targetId,其他targetId默认为0

NowCoder_13_2

NowCoder_13_3

5.功能测试

NowCoder_13_4

NowCoder_13_5

image-20220721153222758

NowCoder_13_7

NowCoder_13_8

comment数据库信息查看:

NowCoder_13_9

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

(仿牛客社区项目)Java开发笔记3.5:添加评论 的相关文章

  • python之逻辑回归项目实战——信用卡欺诈检测

    信用卡欺诈检测 1 项目介绍2 项目背景3 分析项目4 数据读取与分析4 1 加载数据4 2 查看数据的标签分布 5 数据预处理5 1 特征标准化5 2 使用下采样解决样本数据不均衡 6 训练数据即划分数据集7 模型建立7 1 sklear
  • C++ 全局变量的跨文件使用

    文章目录 前言一 extern的使用二 容易犯的错误 前言 在写C 43 43 工程文件的时候 xff0c 往往会用到一些所有类都使用的数据 xff0c 比如数据文件等 xff0c 一种写法是写成静态类 xff0c 调用数据时使用类名加属性
  • VS2019使用C++创建winform界面

    用C 43 43 实现winform界面 算是对上一篇文章的补充吧 xff0c 实际上不需要那么繁琐也可以做到 事先准备 打开VS xff0c 新建一个CLR项目 如果在选项中没有发现CLR项目 xff1a 1 找到Visual Studi
  • c++面试题(亲测常问)

    注意 xff1a 此题为我自己面试被问到的 xff0c 及一些摘抄的 xff0c 如有侵权请联系我马上删除 xff01 1 2 32位指针地址所占字节数 为四 举例说明 xff1a char p char test 10 p 61 test
  • torchvision与torch的对应关系及下载链接

    https github com pytorch vision 另外 xff1a Ubuntu18下编译安装torchvision C 43 43 API的详细过程
  • Logisim计算机组成原理实验16位无符号比较器设计

    Logisim用4位无符号比较器构建16位无符号比较器 4位无符号比较器设计思路表达式构建 16位无符号比较器构建思路构建 4位无符号比较器设计 思路 不同位之间进行比较 xff0c 高位优先 真值表太麻烦 xff0c 可以利用表达式进行构
  • React+hooks+TS练习

    一 初始化项目 通过create react app命令创建项目 xff0c template表示使用typescript xff08 node版本高于14才能使用npx xff09 npx create span class token
  • 基于Python的信用卡欺诈检测机器学习案例报告

    本报告借助Python语言探究了在机器学习中 面对一个大型的人与人之间交易的数据集 如何尽快处理大量数据并区分某交易记录是正常的用户行为还是潜在的信用卡欺诈行为 最终通过构建分类模型来对欺诈交易进行分类区分 并通过恰当的方式对构建的模型进行
  • 一个既有趣又简单的整人代码——关机代码

    这一篇博客来的比我的预计时间要长啊 xff0c 在这一周多的时间里 xff0c 我几乎很少有休息和出去玩耍的时间 说实话 xff0c 这样忙碌的生活给我的感觉还是蛮好的 xff0c 让我有一种很充实的感觉 xff0c 有种自己在与时间赛跑的
  • 【CMake】CMakeList编写整理

    什么是CMake 如果软件想跨平台 xff0c 必须要保证能够在不同平台编译 而如果使用 Make 工具 xff0c 就得为每一种标准写一次 Makefile CMake 就是针对上面问题所设计的工具 xff1a 它首先允许开发者编写一种平
  • 解决 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform...警告

    解决 WARN util NativeCodeLoader Unable to load native hadoop library for your platform using builtin java classes where ap
  • Vue获取数组的数组数据

    Q xff1a 如何在vue获取数组的数组 xff1f A xff1a 用到js的map对象方法 一 data里要先定义好有两个数组 二 主要代码 这样就可以获取到数组的子数组数据
  • Ubuntu18.04 GAAS学习笔记

    GAAS学习笔记 1 环境构建1 1 依赖项安装1 2 ros安装1 3 MAVROS安装1 4 PX4 Firmware安装 全程参考官方文档 xff0c 总结遇见的错误 xff1a https gaas gitbook io guide
  • ArUco标定板生成与打印

    链接如下 xff1a https span class token punctuation span span class token operator span chev span class token punctuation span
  • ROS工作空间与功能包

    工作空间 工作空间 xff08 workspace xff09 是一个存放工程开发相关文件的文件夹 xff0c 其目录下有 xff1a src xff1a 代码空间 xff08 Source Space xff09 build xff1a
  • Ubuntu20.04安装UHD及GUN Radio3.9

    目录 1 安装UHD依赖库及UHD 2 安装GNU Radio3 9 3 1 安装UHD依赖库及UHD 总结自 xff1a USRP Hardware Driver and USRP Manual Building and Installi
  • ros安装的依赖问题

    问题描述 xff1a ros kinetic desktop full 依赖 ros kinetic desktop 但是它将不会被安装 依赖 ros kinetic perception 但是它将不会被安装 依赖 ros kinetic
  • STM32MP157驱动开发——字符设备驱动

    一 简介 字符设备是 Linux 驱动中最基本的一类设备驱动 xff0c 字符设备就是一个一个字节 xff0c 按照字节 流进行读写操作的设备 xff0c 读写数据是分先后顺序的 比如我们最常见的点灯 按键 IIC SPI xff0c LC
  • Java样卷

    一 问答题 请解释一下Java语言的主要特点 至少说明五个特点 进程和线程的概念是什么 xff1f 两者有什么区别和联系 什么是流 xff1f 什么是字节流 xff1f 什么是字符流 xff1f 字节流和字符流的差别是什么 xff1f 二
  • CodeBlocks如何将英文环境改为中文

    一 下载汉化包 xff08 链接如下 xff09 链接 xff1a https pan baidu com s 1U FMZuFvFQ9 70whXcIwQ 提取码 xff1a 2333 二 选择路径 将汉化包中的文件 xff08 Code

随机推荐