下面的类是从 API 调用返回的结构,减去 primaryKey、parentId 和 depth。我的目标是使用递归 CTE 在 Room DB 中构建一个闭包表。
class Category {
public Integer primaryKey;
public String parentId;
public Integer depth;
public String categoryId;
public String name;
public String pluralName;
public String shortName;
@Ignore public List<Category> categories;
}
当返回的 POJO 从可观察对象发出时,我尝试遍历树。问题在于 categoryId==parentId 的某些传递闭包的深度不正确。
for(Category category: categories){
List<Category> tree = new ArrayList<>();
buildCategoryClosureTable(category, tree, 0);
}
void buildCategoryClosureTable(Category target, List<Category> tree, Integer depth){
tree.add(target);
if(!target.categories.isEmpty()){
depth++;
do{
Category category = target.categories.remove(0);
buildFoursquareCategoryClosureTable(category, tree, depth);
}while(!target.categories.isEmpty());
}
for(Category category : tree){
FoursquareCategory foursquareCategory = new FoursquareCategory(target, category.categoryId, depth);
insertFoursquareCategoryIntoBaseTable(foursquareCategory);
depth--;
}
tree.remove(target);
}
那么...如何使用递归 CTE 在 Room DB 中构建闭包表?