最近工作需要做一個評論功能,除了展示評論之外,還需要展示評論回覆,評論的回覆的回覆,這裏就用到了遞歸實現評論的多級回覆。
評論實體
數據庫存儲字段: id 評論id、parent_id 回覆評論id、message 消息。其中如果評論不是回覆評論,parent_id 為-1。
創建一個評論實體 Comment:
public class Comment {
/**
* id
*/
private Integer id;
/**
* 父類id
*/
private Integer parentId;
/**
* 消息
*/
private String message;
}
查詢到所有的評論數據。方便展示樹形數據,對Comment添加回複列表
List<ViewComment> children
ViewComment結構如下:
// 展示樹形數據
public class ViewComment {
/**
* id
*/
private Integer id;
/**
* 父類id
*/
private Integer parentId;
/**
* 消息
*/
private String message;
/**
* 回覆列表
*/
private List<ViewComment> children = new ArrayList<>();
}
添加非回覆評論
非回覆評論的parent_id為-1,先找到非回覆評論:
List<ViewComment> viewCommentList = new ArrayList<>();
// 添加模擬數據
Comment comment1 = new Comment(1,-1,"留言1");
Comment comment2 = new Comment(2,-1,"留言2");
Comment comment3 = new Comment(3,1,"留言3,回覆留言1");
Comment comment4 = new Comment(4,1,"留言4,回覆留言1");
Comment comment5 = new Comment(5,2,"留言5,回覆留言2");
Comment comment6 = new Comment(6,3,"留言6,回覆留言3");
//添加非回覆評論
for (Comment comment : commentList) {
if (comment.getParentId() == -1) {
ViewComment viewComment = new ViewComment();
BeanUtils.copyProperties(comment,viewComment);
viewCommentList.add(viewComment);
}
}
遞歸添加回複評論
遍歷每條非回覆評論,遞歸添加回複評論:
for(ViewComment viewComment : viewCommentList) {
add(viewComment,commentList);
}
private void add(ViewComment rootViewComment, List<Comment> commentList) {
for (Comment comment : commentList) {
// 找到匹配的 parentId
if (rootViewComment.getId().equals(comment.getParentId())) {
ViewComment viewComment = new ViewComment();
BeanUtils.copyProperties(comment,viewComment);
rootViewComment.getChildren().add(viewComment);
//遞歸調用
add(viewComment,commentList);
}
}
}
- 遍歷每條非回覆評論。
- 非回覆評論
id匹配到評論的parentId,添加到該評論的children列表中。 - 遞歸調用。
結果展示:
github 源碼
https://github.com/jeremylai7/java-codes/tree/master/basis/src/main/java/recurve