添加评论

tong11 / 2023-08-25 / 原文

添加评论

数据层

增加评论数据

修改帖子的评论数量

在接口定义CommentMapper

//添加评论
int insertComment(Comment comment);

DiscussPostMapper

//添加评论
int updateCommentCount(int id, int commentCount);

业务层

处理添加评论的业务

先增加评论,再更新帖子的评论数量

Comment-mapper.xml

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

定义接口CommunityConstant

/**
* 实体类型: 帖子
*/
int ENTITY_TYPE_POST = 1;

/**
* 实体类型: 评论
*/
int ENTITY_TYPE_COMMENT = 2;

CommentService

@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;
}

表现层

处理添加评论数据的请求

设置添加评论的表单

CommentController

//添加评论
@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;
  }

测试结果