關於遞迴呼叫,實現樹形選單的樣式
一:需求
現有以需求就是把某一個帖子的全部評論展示出來。
二:分析
關於對帖子的評論分為主評論和子評論,主評論就是對帖子的直接評論,子評論就是對評論的評論。
三:思路
先獲取某一個帖子的全部主評論,遞迴判斷是否有子評論,獲取子評論。
四:編碼
實體類:
1 import java.util.Date; 2 import java.util.List; 3 4 import com.fasterxml.jackson.annotation.JsonFormat; 5 6 import lombok.Data; 7 @Data 8 public class BsChannelPostReply { 9private long replyId; 10private String niceName; 11@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") 12private Date replyDate; 13private String content; 14private long directRepliedId;//回覆的直接評論的replyId 15private List<BsChannelPostReply> children;//下面的子評論 16 }
獲取主評論列表,和遞迴全部子評論:
1 @Override 2@Datasource(value="community")//切換資料來源 3public List<BsChannelPostReply> getMainReply(int postId) { 4// TODO Auto-generated method stub 5List<BsChannelPostReply> listMain=dao.getMainReply(postId);//獲取主評論 6if(listMain.size()>=0){//如果主評論不為空 7for (BsChannelPostReply bsChannelPostReply : listMain) { 8bsChannelPostReply.setChildren(getMainReplyChildren(bsChannelPostReply.getReplyId()));//載入子評論 9} 10} 11return listMain; 12} 13 14@Override 15@Datasource(value="community")//切換資料來源 16public List<BsChannelPostReply> getMainReplyChildren(long replyId) { 17// TODO Auto-generated method stub 18List<BsChannelPostReply> listChildren=dao.getMainReplyChildren(replyId);//根據當前的replayId獲取當前級子評論列表 19if(listChildren.size()>=0){ 20for (BsChannelPostReply bsChannelPostReply : listChildren) { 21bsChannelPostReply.setChildren(getMainReplyChildren(bsChannelPostReply.getReplyId()));//在判斷當前子評論是否還有子評論,遞迴呼叫,直到沒有子評論 22} 23} 24return listChildren; 25}
五:效果
根據這樣的遞迴呼叫就可以實現理論上的獲取無極限的子評論列表。