携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第14天,点击查看活动详情
3.6 添加评论
数据访问层(dao)
首先是在 CommentMapper 接口中增加两个方法添加评论:
int insertComment(Comment comment);
/**
* 插入一条评论
*/
<sql id="insertFields">
user_id, entity_type, entity_id, target_id, content, status, create_time
</sql>
<insert id="insertComment" parameterType="com.nowcoder.community.entity.Comment">
insert into comment(<include refid="insertFields"></include>)
values(#{userId}, #{entityType}, #{entityId}, #{targetId}, #{content}, #{status}, #{createTime})
</insert>
然后我们需要在 DiscussPostMapper 接口中增加一个更新帖子数量的方法:
int updateCommentCount(int id, int commentCount);
/**
* 根据帖子id更新评论数量
*/
然后是对应的mapper配置文件
<update id="updateCommentCount">
update discuss_post set comment_count = #{commentCount}
where id = #{id}
</update>
业务层(Service)
我们先在 DiscussPostService 中加一个更新评论数量的方法,然后在 CommentService 中开发时可以依赖于 DiscussPostService 组件
DiscussPostService :
public int updateCommentCount(int id, int commentCount){
return discussPostMapper.updateCommentCount(id, commentCount);
}
CommentService:
为了方便使用常量,CommentService要实现常量接口 CommunityConstant
@Autowired
private SensitiveFilter sensitiveFilter;
@Autowired
private DiscussPostService discussPostService;
// 增加评论数量,另外,因为是两个DML操作:增加评论、更新评论数量,所以交给事务管理
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED) // 事务级别、传播机制
public int addComment(Comment comment){
if(comment == null){
throw new IllegalArgumentException("参数不能为空!");
}
// 添加评论 转义html标记 过滤敏感词
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;
}
表现层(controller 和 thymeleaf 模板)
新建一个 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;
}
}
然后就是处理 discuss-detail.html 模板了
回复有三种类型:
- 一种是直接在帖子最下面回复
- 一种是回复别人对于帖子的评论的评论
- 最后一种是回复别人评论别人的评论
测试
经过自己测试,三种方式的评论都测试成功!