資料庫多層資料運用遞迴演算法生成樹形資料
第一步:準備表結構及對應的表資料
1.表結構
create table City
(
id char(32) not null,
name varchar2(30),
parent_id char(32) //父級欄位
)
2.插入資料
insert into City (id, name, parent_id) values (1, '書籍', 0);
insert into City (id, name, parent_id) values (2, '科普書籍', 1);
insert into City (id, name, parent_id) values (3, '教科書籍', 1);
insert into City (id, name, parent_id) values (4, '童話書籍', 1);
insert into City (id, name, parent_id) values (5, '語文', 3);
insert into City (id, name, parent_id) values (6, '數學', 3);
insert into City (id, name, parent_id) values (7, '九年級上冊語文書', 5);
insert into City (id, name, parent_id) values (8, '九年級下冊語文書', 5);
insert into City (id, name, parent_id) values (9, '九年級上冊數學書', 6);
insert into City (id, name, parent_id) values (10, '九年級下冊數學書', 6);
insert into City (id, name, parent_id) values (11, '十萬個為什麼', 2);
insert into City (id, name, parent_id) values (12, '格林童話', 4);
第二步:建立Entity的Bean物件
1.建立Bean
public class CityEntity implements Serializable {
private String id;
private String name;
private String parent_id;
//getter,setter
}
2.建立對外輸出的響應Bean
public class CityResponse {
private String id;
private String name;
private String parent_id;
private List children = new ArrayList();
//getter,setter
public CityResponse() {
}
public CityResponse(CityEntity entity) {
this.set(entity);
}
public CityResponse set(CityEntity entity) {
this.id = entity.getId;
this.name = entity.getName;
this.parentId = entity.getParentId;
return this;
}
}
第三步 進行遞迴遍歷,生成樹形介面
1.測試程式碼:
public class CityTest {
@Test
public void cityTree() throws Exception{
System.out.println(recursiveTree(1));
}
2.遞迴方法
public CityResponse getTreeModule(String id) throws Exception {
CityResponse firstTreeResponse = new CityResponse();
//根據id獲取節點物件(SELECT * FROM City c WHERE c.id=?)
CityEntity entity = cityService.findById(id);
firstTreeResponse.set(entity);
//查詢id下的所有子節點(SELECT * FROM City c WHERE c.parent_id=?)
List<CityEntity> entities = cityService.findByParentId(id);
List<CityResponse> treeResponses = new ArrayList<CityResponse>();
CityResponse secondTreeResponse = null;
for (CityEntity cityEntity : entities) {
secondTreeResponse = new CityResponse();
treeResponses.add(secondTreeResponse.set(CityEntity));
}
CityResponse cityTreeResponse = null;
for (CityResponse child : treeResponses) {
cityTreeResponse = getTreeModule(child.getId());//開始遞迴
firstTreeResponse.getChildren().add(cityTreeResponse);
}
return firstTreeResponse;
}
3.輸出(省略)