我想获得类别的递归数据结构。
<小时/> OOM结构:
类别应管理列表或一组(子)类别。
<小时/> ROM结构:
ROM的物理结构:
category (_id_, title)
overAndSubCategories (ocId, scId)
overAndSubCategories
的两个属性都是外键,并引用category
的ID。
类别的标题是唯一的,可能是主键,但到目前为止,greenDao不支持字符串作为主键。所以我在记录中添加了一个id。
GreenDao不支持多对多的关系。我能够实现解决此结构问题的等效方案吗?
*两张图片均由 yEd
提供答案 0 :(得分:1)
我不确定这个解决方案是正确的还是最好的,因为我不知道我做了什么,但它有效。
计划生成器:
final Entity category = schema.addEntity("Category");
category.addIdProperty();
category.addStringProperty("Name").notNull().unique().index();
final Entity overSubCategory = schema.addEntity("OverSubCategory");
// no own id! we do not want to load objects of this type
final Property fkOverCategory = overSubCategory.addLongProperty("IdO").notNull().getProperty();
final Property fkSubCategory = overSubCategory.addLongProperty("IdS").notNull().getProperty();
overSubCategory.addToOne(category, fkOverCategory, "OverCategory");
overSubCategory.addToOne(category, fkSubCategory, "SubCategory");
使用此方案:
/* # write # */
final CategoryDao categoryDao = session.getCategoryDao();
final OverSubCategoryDao overSubCategory = session.getOverSubCategoryDao();
// overcategories
final Category oC1 = new Category(1l, "food and drink");
final Category oC2 = new Category(2l, "party");
// subcategories
final Category sC1 = new Category(3l, "junkfood");
final Category sC2 = new Category(4l, "restaurante");
final Category sC3 = new Category(5l, "pub");
categoryDao.insert(oC1);
categoryDao.insert(oC2);
categoryDao.insert(sC1);
categoryDao.insert(sC2);
categoryDao.insert(sC3);
overSubCategory.insert( new OverSubCategory(oC1.getId(), sC1.getId()) );
overSubCategory.insert( new OverSubCategory(oC1.getId(), sC2.getId()) );
overSubCategory.insert( new OverSubCategory(oC1.getId(), sC3.getId()) );
overSubCategory.insert( new OverSubCategory(oC2.getId(), sC3.getId()) );
/* # read # */
final QueryBuilder<Category> cqb = categoryDao.queryBuilder();
// all categories that are subcategories and ...
final Join joinOverSubCategories = cqb.join(OverSubCategory.class, OverSubCategoryDao.Properties.IdS);
// ... whose overcategories ...
final Join joinSubCategories = cqb.join(joinOverSubCategories, OverSubCategoryDao.Properties.IdO, Category.class, CategoryDao.Properties.Id);
// ... named "food and drink".
joinSubCategories.where(CategoryDao.Properties.Name.eq("food and drink"));
final List<Category> someSubcategories = cqb.list();
两个连接加上一个条件似乎有点多。 更好的解决方案是可取的。