溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot如何實現(xiàn)無限級評論回復(fù)功能

發(fā)布時間:2023-03-24 14:00:23 來源:億速云 閱讀:168 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“SpringBoot如何實現(xiàn)無限級評論回復(fù)功能”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

1 數(shù)據(jù)庫表結(jié)構(gòu)設(shè)計

表結(jié)構(gòu):

CREATE TABLE `comment` (
  `id` bigint(18) NOT NULL AUTO_INCREMENT,
  `parent_id` bigint(18) NOT NULL DEFAULT '0',
  `content` text NOT NULL COMMENT '內(nèi)容',
  `author` varchar(20) NOT NULL COMMENT '評論人',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '評論時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;

數(shù)據(jù)添加:

INSERT INTO `comment` (`id`, `parent_id`, `content`, `author`, `create_time`) VALUES (1, 0, '這是評論1', '吳名氏', '2023-02-20 17:11:16');
INSERT INTO `comment` (`id`, `parent_id`, `content`, `author`, `create_time`) VALUES (2, 1, '我回復(fù)了第一條評論', '吳名氏', '2023-02-20 17:12:00');
INSERT INTO `comment` (`id`, `parent_id`, `content`, `author`, `create_time`) VALUES (3, 2, '我回復(fù)了第一條評論的第一條回復(fù)', '吳名氏', '2023-02-20 17:12:13');
INSERT INTO `comment` (`id`, `parent_id`, `content`, `author`, `create_time`) VALUES (4, 2, '我回復(fù)了第一條評論的第二條回復(fù)', '吳名氏', '2023-02-21 09:23:14');
INSERT INTO `comment` (`id`, `parent_id`, `content`, `author`, `create_time`) VALUES (5, 0, '這是評論2', '吳名氏', '2023-02-21 09:41:02');
INSERT INTO `comment` (`id`, `parent_id`, `content`, `author`, `create_time`) VALUES (6, 3, '我回復(fù)了第一條評論的第一條回復(fù)的第一條回復(fù)', '吳名氏', '2023-02-21 09:56:27');

添加后的數(shù)據(jù):

SpringBoot如何實現(xiàn)無限級評論回復(fù)功能

2 方案一

方案一先返回評論列表,再根據(jù)評論id返回回復(fù)列表,以此循環(huán),具體代碼下文進行展示

2.1 控制層CommentOneController.java

/**
 * 方案一
 * @author wuKeFan
 * @date 2023-02-20 16:58:08
 */
@Slf4j
@RestController
@RequestMapping("/one/comment")
public class CommentOneController {
 
    @Resource
    private CommentService commentService;
 
    @GetMapping("/")
    public List<Comment> getList() {
        return commentService.getList();
    }
 
    @GetMapping("/{id}")
    public Comment getCommentById(@PathVariable Long id) {
        return commentService.getById(id);
    }
 
    @GetMapping("/parent/{parentId}")
    public List<Comment> getCommentByParentId(@PathVariable Long parentId) {
        return commentService.getCommentByParentId(parentId);
    }
 
    @PostMapping("/")
    public void addComment(@RequestBody Comment comment) {
        commentService.addComment(comment);
    }
 
}

2.2 service類CommentService.java

/**
 * service類
 * @author wuKeFan
 * @date 2023-02-20 16:55:23
 */
public interface CommentService {
 
    List<Comment> getCommentByParentId(Long parentId);
 
    void addComment(Comment comment);
 
    Comment getById(Long id);
 
    List<Comment> getList();
}

2.3 service實現(xiàn)類CommentServiceImpl.java

/**
 * @author wuKeFan
 * @date 2023-02-20 16:56:00
 */
@Service
public class CommentServiceImpl implements CommentService{
 
    @Resource
    private CommentMapper baseMapper;
 
    @Override
    public List<Comment> getCommentByParentId(Long parentId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        return baseMapper.selectList(queryWrapper);
    }
 
    @Override
    public void addComment(Comment comment) {
        baseMapper.insert(comment);
    }
 
    @Override
    public Comment getById(Long id) {
        return baseMapper.selectById(id);
    }
 
    @Override
    public List<Comment> getList() {
        return baseMapper.selectList(new QueryWrapper<Comment>().lambda().eq(Comment::getParentId, 0));
    }
 
}

2.4 數(shù)據(jù)庫持久層類CommentMapper.java

/**
 * mapper類
 * @author wuKeFan
 * @date 2023-02-20 16:53:59
 */
@Repository
public interface CommentMapper extends BaseMapper<Comment> {
 
}

2.5 實體類Comment.java

/**
 * 評論表實體類
 * @author wuKeFan
 * @date 2023-02-20 16:53:24
 */
@Data
@TableName("comment")
public class Comment {
    @TableId(type = IdType.AUTO)
    private Long id;
    private Long parentId;
    private String content;
    private String author;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;
}

2.6 使用Postman請求接口,查看返回數(shù)據(jù)

2.6.1 請求評論列表接口(本地的url為:http://localhost:8081/one/comment/ ,GET請求),請求結(jié)果如圖

SpringBoot如何實現(xiàn)無限級評論回復(fù)功能

2.6.2 根據(jù)評論id(或者回復(fù)id)返回回復(fù)列表(本地url為:http://localhost:8081/one/comment/parent/1 ,GET請求),請求結(jié)果如圖

SpringBoot如何實現(xiàn)無限級評論回復(fù)功能

3 方案二

方案二采用的是將數(shù)據(jù)裝到一個類似樹的數(shù)據(jù)結(jié)構(gòu),然后返回,數(shù)據(jù)如果多的話,可以根據(jù)評論列表進行分頁

3.1 控制層CommentTwoController.java

/**
 * @author wuKeFan
 * @date 2023-02-20 17:30:45
 */
@Slf4j
@RestController
@RequestMapping("/two/comment")
public class CommentTwoController {
 
    @Resource
    private CommentService commentService;
 
    @GetMapping("/")
    public List<CommentDTO> getAllComments() {
       return commentService.getAllComments();
    }
 
    @PostMapping("/")
    public void addComment(@RequestBody Comment comment) {
        commentService.addComment(comment);
    }
}

3.2 service類CommentService.java

/**
 * service類
 * @author wuKeFan
 * @date 2023-02-20 16:55:23
 */
public interface CommentService {
 
    void addComment(Comment comment);
 
    void setChildren(CommentDTO commentDTO);
 
    List<CommentDTO> getAllComments();
}

3.3 service實現(xiàn)類CommentServiceImpl.java

/**
 * @author wuKeFan
 * @date 2023-02-20 16:56:00
 */
@Service
public class CommentServiceImpl implements CommentService{
 
    @Resource
    private CommentMapper baseMapper;
 
    @Override
    public void addComment(Comment comment) {
        baseMapper.insert(comment);
    }
 
    @Override
    public List<CommentDTO> getAllComments() {
        List<CommentDTO> rootComments = baseMapper.findByParentId(0L);
        rootComments.forEach(this::setChildren);
        return rootComments;
    }
 
    /**
     * 遞歸獲取
     * @param commentDTO 參數(shù)
     */
    @Override
    public void setChildren(CommentDTO commentDTO){
        List<CommentDTO> children = baseMapper.findByParentId(commentDTO.getId());
        if (!children.isEmpty()) {
            commentDTO.setChildren(children);
            children.forEach(this::setChildren);
        }
    }
 
}

3.4 數(shù)據(jù)庫持久層類CommentMapper.java

/**
 * mapper類
 * @author wuKeFan
 * @date 2023-02-20 16:53:59
 */
@Repository
public interface CommentMapper extends BaseMapper<Comment> {
 
    @Select("SELECT id, parent_id as parentId, content, author, create_time as createTime FROM comment WHERE parent_id = #{parentId}")
    List<CommentDTO> findByParentId(Long parentId);
 
}

3.5 實體類CommentDTO.java

/**
 * 遞歸方式實體類
 * @author wuKeFan
 * @date 2023-02-20 17:26:48
 */
@Data
public class CommentDTO {
 
    private Long id;
    private Long parentId;
    private String content;
    private String author;
    private List<CommentDTO> children;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;
 
}

3.6 使用Postman請求接口,查看返回數(shù)據(jù)

3.6.1 通過遞歸的方式以樹的數(shù)據(jù)結(jié)構(gòu)返回(本地url為:http://localhost:8081/two/comment/ ,GET請求),請求結(jié)果如圖

SpringBoot如何實現(xiàn)無限級評論回復(fù)功能

返回的json格式如圖:

[
    {
        "id": 1,
        "parentId": 0,
        "content": "這是評論1",
        "author": "吳名氏",
        "children": [
            {
                "id": 2,
                "parentId": 1,
                "content": "我回復(fù)了第一條評論",
                "author": "吳名氏",
                "children": [
                    {
                        "id": 3,
                        "parentId": 2,
                        "content": "我回復(fù)了第一條評論的第一條回復(fù)",
                        "author": "吳名氏",
                        "children": [
                            {
                                "id": 6,
                                "parentId": 3,
                                "content": "我回復(fù)了第一條評論的第一條回復(fù)的第一條回復(fù)",
                                "author": "吳名氏",
                                "children": null,
                                "createTime": "2023-02-21 09:56:27"
                            }
                        ],
                        "createTime": "2023-02-20 17:12:13"
                    },
                    {
                        "id": 4,
                        "parentId": 2,
                        "content": "我回復(fù)了第一條評論的第二條回復(fù)",
                        "author": "吳名氏",
                        "children": null,
                        "createTime": "2023-02-21 09:23:14"
                    }
                ],
                "createTime": "2023-02-20 17:12:00"
            }
        ],
        "createTime": "2023-02-20 17:11:16"
    },
    {
        "id": 5,
        "parentId": 0,
        "content": "這是評論2",
        "author": "吳名氏",
        "children": null,
        "createTime": "2023-02-21 09:41:02"
    }
]

4 方案三

方案三是將所有數(shù)據(jù)用遞歸的SQL查出來,再把數(shù)據(jù)解析成樹,返回結(jié)果,適合數(shù)據(jù)較少的情況下,且MySQL版本需要在8.0以上

4.1 控制層CommentThreeController.java

/**
 * @author wuKeFan
 * @date 2023-02-20 17:30:45
 */
@Slf4j
@RestController
@RequestMapping("/three/comment")
public class CommentThreeController {
 
    @Resource
    private CommentService commentService;
 
    @GetMapping("/")
    public List<CommentDTO> getAllCommentsBySql() {
       return commentService.getAllCommentsBySql();
    }
 
    @PostMapping("/")
    public void addComment(@RequestBody Comment comment) {
        commentService.addComment(comment);
    }
}

4.2 service類CommentService.java

/**
 * service類
 * @author wuKeFan
 * @date 2023-02-20 16:55:23
 */
public interface CommentService {
 
    List<CommentDTO> getAllCommentsBySql();
 
}

4.3 service實現(xiàn)類CommentServiceImpl.java

/**
 * @author wuKeFan
 * @date 2023-02-20 16:56:00
 */
@Service
public class CommentServiceImpl implements CommentService{
 
    @Resource
    private CommentMapper baseMapper;
 
    /**
     * 遞歸獲取
     * @param commentDTO 參數(shù)
     */
    @Override
    public void setChildren(CommentDTO commentDTO){
        List<CommentDTO> children = baseMapper.findByParentId(commentDTO.getId());
        if (!children.isEmpty()) {
            commentDTO.setChildren(children);
            children.forEach(this::setChildren);
        }
    }
 
}

4.4 數(shù)據(jù)庫持久層類CommentMapper.java

/**
 * mapper類
 * @author wuKeFan
 * @date 2023-02-20 16:53:59
 */
@Repository
public interface CommentMapper extends BaseMapper<Comment> {
 
    @DS("localhost80")
    List<CommentDTO> getAllCommentsBySql();
 
}

4.5 實體類Comment.java

/**
 * 評論表實體類
 * @author wuKeFan
 * @date 2023-02-20 16:53:24
 */
@Data
@TableName("comment")
public class Comment {
    @TableId(type = IdType.AUTO)
    private Long id;
    private Long parentId;
    private String content;
    private String author;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;
    private Integer level;
}

4.6 使用Postman請求接口,查看返回數(shù)據(jù)

4.6.1 通過遞歸的方式以樹的數(shù)據(jù)結(jié)構(gòu)返回(本地url為:http://localhost:8081/three/comment/ ,GET請求),請求結(jié)果如圖

SpringBoot如何實現(xiàn)無限級評論回復(fù)功能

返回的json格式如圖:

[
    {
        "id": 1,
        "parentId": 0,
        "content": "這是評論1",
        "author": "吳名氏",
        "children": [
            {
                "id": 2,
                "parentId": 1,
                "content": "我回復(fù)了第一條評論",
                "author": "吳名氏",
                "children": [
                    {
                        "id": 3,
                        "parentId": 2,
                        "content": "我回復(fù)了第一條評論的第一條回復(fù)",
                        "author": "吳名氏",
                        "children": [
                            {
                                "id": 6,
                                "parentId": 3,
                                "content": "我回復(fù)了第一條評論的第一條回復(fù)的第一條回復(fù)",
                                "author": "吳名氏",
                                "children": [],
                                "createTime": "2023-02-21 09:56:27",
                                "level": 4
                            }
                        ],
                        "createTime": "2023-02-20 17:12:13",
                        "level": 3
                    },
                    {
                        "id": 4,
                        "parentId": 2,
                        "content": "我回復(fù)了第一條評論的第二條回復(fù)",
                        "author": "吳名氏",
                        "children": [],
                        "createTime": "2023-02-21 09:23:14",
                        "level": 3
                    }
                ],
                "createTime": "2023-02-20 17:12:00",
                "level": 2
            }
        ],
        "createTime": "2023-02-20 17:11:16",
        "level": 1
    },
    {
        "id": 5,
        "parentId": 0,
        "content": "這是評論2",
        "author": "吳名氏",
        "children": [],
        "createTime": "2023-02-21 09:41:02",
        "level": 1
    }
]

“SpringBoot如何實現(xiàn)無限級評論回復(fù)功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI