網站前臺的三級聯動數據封裝

我在進行項目時候遇到了一個進行數據封裝的一個功能,進行數據的封裝的功能也挺複雜,來回試了好幾十種方法.最後使用的是這種方法.sql

使用一個pojo進行封裝兩個數據,一個是list一個是實體類.app

具體代碼爲ide

 

@RequestMapping("/findByParentId")
    public List<ItemCatList2VO> findByParentId(Long parentId) {

        ArrayList<ItemCatList2VO> list1 = new ArrayList<>();

//       獲取到的第一層結果集
        List<ItemCat> itemCatList1 = itemCatService.findByParent(parentId);
        //將這份數據進行封裝
        for (ItemCat itemCat1 : itemCatList1) {
            //建立pojo對象
            ItemCatList2VO<ItemCatList2VO> list2VO1 = new ItemCatList2VO<>();

            ArrayList<ItemCatList2VO> list2 = new ArrayList<>();
            //獲取第二層的數據
            Long id1 = itemCat1.getId();
            List<ItemCat> itemCatList2 = itemCatService.findByParent(id1);
            for (ItemCat itemCat2 : itemCatList2) {
                //建立pojo對象
                ItemCatList2VO<ItemCat> list2VO2 = new ItemCatList2VO<>();
                Long id2 = itemCat2.getId();
                List<ItemCat> itemCatList3 = itemCatService.findByParent(id2);
                list2VO2.setItemCat(itemCat2);
                list2VO2.setList(itemCatList3);
                list2.add(list2VO2);
            }

            //封裝進pojo
            list2VO1.setItemCat(itemCat1);
            list2VO1.setList(list2);
            list1.add(list2VO1);
        }
        return list1;
    }

而後我使用的是有limit條件的查詢,因此本身手動拼了一個sql.這裏沒有向上貼代碼this

實現思路:3d

  首先建立pojo類對象

public class ItemCatList2VO <T>implements Serializable {
//實體類
    private ItemCat itemCat;
//list集合.用來存儲經過父id進行查詢的結果.
    private List<T> list;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ItemCatList2VO<?> that = (ItemCatList2VO<?>) o;
        return Objects.equals(itemCat, that.itemCat) &&
                Objects.equals(list, that.list);
    }

    @Override
    public int hashCode() {

        return Objects.hash(itemCat, list);
    }

    public ItemCat getItemCat() {

        return itemCat;
    }

    public void setItemCat(ItemCat itemCat) {
        this.itemCat = itemCat;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }
}

這是一個分爲須要封裝三層,我作的時候思路沒有那麼開闊,因此我是先封裝了而後再在這個基礎上進行的第三層的封裝. blog

  第一層就是:在for循環的過程當中,將第一層數據中的itemCat和第二層中的結果集封裝在pojo中,而後再封裝到list集合中.get

  第二層就是在第二個for循環中,將第二層數據中的itemCat和第三層中的結果集封裝在pojo中,而後再封裝到list集合中.hash

 

而後在頁面上使用it

作出來之後是這樣的一個結構.能夠使用循環遍歷的方式,將這個數據取出來.

當在第二級和第三級的div在同級的狀況下的時候,能夠使用:

將數據取出來.我以爲在封裝數據的餓時候挺難的.

總結:使用list和pojo將對象進行封裝,封裝完成後,扔到頁面進行解析.

相關文章
相關標籤/搜索