我在进行项目时候遇到了一个进行数据封装的一个功能,进行数据的封装的功能也挺复杂,来回试了好几十种方法.最后使用的是这种方法.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将对象进行封装,封装完成后,扔到页面进行解析.