添加评论(十三)
一、数据层
- 增加评论数据。
- 修改帖子的评论数量。
由Mybatis plus实现。
二、业务层
- 处理添加评论的业务:先增加评论、再更新帖子的评论数量。
DiscussPostService
接口
public interface DiscussPostService extends IService<DiscussPost> {
// ...
boolean updateCommentCount(int id, int commentCount);
}
DiscussPostServiceImpl
@Service
public class DiscussPostServiceImpl extends ServiceImpl<DiscussPostMapper, DiscussPost>
implements DiscussPostService{
// ...
@Override
public boolean updateCommentCount(int id, int commentCount) {
LambdaUpdateWrapper<DiscussPost> luw = new LambdaUpdateWrapper<>();
luw.set(DiscussPost::getCommentCount,commentCount)
.eq(DiscussPost::getId,id);
return this.update(luw);
}
}
CommentService
接口
public interface CommentService extends IService<Comment> {
// ...
boolean addComment(Comment comment);
}
CommentServiceImpl
@Override
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public boolean addComment(Comment comment) {
if (comment == null) {
throw new IllegalArgumentException("参数不能为空!");
}
// 添加评论
comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
comment.setContent(sensitiveFilter.filter(comment.getContent()));
boolean res = this.save(comment);
// 更新帖子评论数量
if (comment.getEntityType() == ENTITY_TYPE_POST) {
int count = this.baseMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
discussPostService.updateCommentCount(comment.getEntityId(), count);
}
return res;
}
三、表现层
- 处理添加评论数据的请求。
- 设置添加评论的表单。
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;
}
}
页面处理,略。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)