网站前台的三级联动数据封装

我在进行项目时候遇到了一个进行数据封装的一个功能,进行数据的封装的功能也挺复杂,来回试了好几十种方法.最后使用的是这种方法.

使用一个pojo进行封装两个数据,一个是list一个是实体类.

具体代码为:

   @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.这里没有向上贴代码

实现思路:

  首先创建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; } }

  这是一个分为需要封装三层,我做的时候思路没有那么开阔,所以我是先封装了然后再在这个基础上进行的第三层的封装. 

  第一层就是:在for循环的过程中,将第一层数据中的itemCat和第二层中的结果集封装在pojo中,然后再封装到list集合中.

  第二层就是在第二个for循环中,将第二层数据中的itemCat和第三层中的结果集封装在pojo中,然后再封装到list集合中.

  

   然后在页面上使用

  做出来以后是这样的一个结构.可以使用循环遍历的方式,将这个数据取出来.

当在第二级和第三级的div在同级的情况下的时候,可以使用:

将数据取出来.我觉得在封装数据的饿时候挺难的.

总结:使用list和pojo将对象进行封装,封装完成后,扔到页面进行解析.

原文地址:https://www.cnblogs.com/qingmuchuanqi48/p/10852674.html