递归查询

public class CategoryDTO{

private Integer id;

private String text;

private Integer childrenCount;

private List<CategoryDTO> children = new ArrayList<CategoryDTO>();


set ...   get....

}

public List<CategoryDTO> findAllCategories(Integer parentId) throws Exception{

List<CategoryDTO> cds = new ArrayList<CategoryDTO>();

List<Object[]> types = tcd.findByParentId(-1);

for(Object[] type : types){

CategoryDTO cd = new CategoryDTO();

cd.setId(Integer.parseInt(type[0].toString()));
cd
.setText(type[1].toString());
Integer childrenCount = (null == type[2] ? 0 : Integer.parseInt(type[2].toString()));

if(childrenCount == 0){

cd.setChildren(null);

} else {

cd.setChildren(getTypes(cd, childrenCount))

}

cds.add(cd);

}

return cds;

}


//递归调用查询子类类别

private List<CategoryDTO> getTypes(CategoryDTO cd, Integer childCount) throws Exception{

List<CategoryDTO> cds = null;

if(childrenCount != 0){

cds = new ArrayList<CategoryDTO>();
List<Object[]> types = tcd.findByParentId(-1);

for(Object[] type : types){

CategoryDTO children = new CategoryDTO();

children .setId(Integer.parseInt(type[0].toString()));
children
.setText(type[1].toString());
Integer childrenCount = (null == type[2] ? 0 : Integer.parseInt(type[2].toString()));

children.setChildrenCount(childrenCount);

cds.add(children);

List<CategoryDTO> types2 = getTypes(children,children.getChildrenCount());

children.setChildren(types2);

}

return cds;

}

}


查询的sql语句: select t1.cid, t1.cname, count(c2.id) from (select c1.id as cid, c1.name as cname from category where pid=?) as t1 left join category c2 on c1.cid = c2.pid group by t1.cid, t1.cname


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值