二级评论关键思路
添加:一级评论父id设为-1,二级评论的父评论父id不为-1的话,则将二级评论设为父评论的父id(听起来有点绕口,其实就是将所有二级评论的父id都设置为一级评论的id)。
查询:使用分布查询,先查出页面上的父评论,再使用分步查询(使用连表应该也可以实现,笔者学艺不精,有能力可以多探索探索)查出父评论下的子评论。
注意
查询二级评论时子查询的resultmap不能使用父评论查询的resultmap,不然会陷入循环导致栈溢出。
评论实体类
@ApiModel("评论实体类")
public class Comment {
@ApiModelProperty("主键自增")
private Integer id;
@ApiModelProperty("用户id")
private Integer userId;
@ApiModelProperty("评论内容")
private String content;
@ApiModelProperty("评论时间")
private String createTime;
@ApiModelProperty("父级评论id,没有父级评论的话则为-1")
private Integer fatherId;
@ApiModelProperty("子集评论集合")
private List<Comment> comments;
}
使用用户id查出相对应的用户信息展示到页面上,在这个实体类的基础上可以增加页面id用来标识该评论所在的页面。
代码实现
service层
//添加评论
@Override
public Result addComment(Comment comment) {
Result result = new Result();
//将二级评论的所有父id都转为一级评论的id
if(comment.getFatherId()!=-1){
int fatherIdById = commentMapper.getFatherIdById(comment.getFatherId());
if(fatherIdById!=-1){
comment.setFatherId(fatherIdById);
}
}
//查询用户是否存在
User user = userMapper.searchUserById(comment.getUserId());
if(user==null){
result.setCode(Code.ADD_ERR);
result.setMsg("add error!the user is not exist!");
return result;
}
//初始化评论对象
comment = new Comment(comment,DateUtil.getCurrentDateString(new Date()),user.getNickname(),user.getPicture(),user.getLocation());
//持久层添加评论
commentMapper.addComment(comment);
result.setData("comment");
result.setMsg("add success!");
result.setCode(Code.ADD_OK);
return result;
}
//查询评论
@Override
public Result getComment(int type , int typeId){
Result result = new Result();
List<Comment> comment = commentMapper.getComment(type, typeId);
result.setCode(Code.GET_OK);
result.setMsg("get success!");
result.setData(comment);
return result;
}
//删除评论
@Override
public Result deleteComment(int commentId) {
Result result = new Result();
if(commentMapper.deleteCommentById(commentId)>0){
result.setCode(Code.DELETE_OK);
result.setMsg("delete success!");
}else{
result.setCode(Code.DELETE_ERR);
result.setMsg("delete error!the result number is zero!");
}
return result;
}
mapper层
<select id="getFatherIdById" resultType="integer">
select father_id from comment where id = #{id};
</select>
<insert id="addComment" useGeneratedKeys="true" keyProperty="id">
insert into comment (type, type_id, user_id, content, create_time, nickname, user_picture, location, father_id)
values (#{type} ,#{typeId} , #{userId} , #{content} , #{createTime} , #{nickname} , #{userPicture} , #{location} , #{fatherId})
</insert>
<select id="getComment" resultMap="Comment">
select * from comment where type = #{type} and type_id = #{typeId} and father_id = -1;
</select>
<select id="getChildComment" resultType="net.wlgzs.core.entity.Comment">
select * from comment where father_id = #{id};
</select>
<delete id="deleteCommentById">
delete from comment where id = #{commentId} or father_id = #{commentId};
</delete>
效果展示:
总结
二级评论思路其实并不难,多摸索就能学会。学习一门编程语言最好的方法还是直接上手敲代码,纸上谈兵不可取。