Flutter ObjectBox嵌套ToOne/ToMany实体存储:是否需重复创建Box?
问题描述
我定义了以下Hive实体:
@Entity() class CategoryData { CategoryData({ this.id = 0, required this.catName, }); @Id() int id; String catName; @Backlink() final subCats = ToMany<SubCatData>(); } @Entity() class SubCatData { SubCatData({ this.id = 0, required this.subCatPair, }); @Id() int id; String subCatPair; @Backlink() final groups = ToMany<GroupData>(); final catData = ToOne<CategoryData>(); } @Entity() class GroupData { GroupData({ this.id = 0, required this.groupPair, }); @Id() int id; String groupPair; @Backlink() final groups = ToMany<Item>(); final subCatData = ToOne<SubCatData>(); } @Entity() class Item { const Item({this.id = 0}); @Id() int id; }
我的需求是在两个独立的存储环境下保存这些实体的实例,目前我考虑的方案是为每个实体分别创建对应两个存储的Box:
// saving the 1's and 2's in 2 different stores: late final Store store1; late final Store store2; late final Box<CategoryData> box1; late final Box<SubCatData> boxsubCat1; late final Box<GroupData> boxGroup1; late final Box<Item> boxItems1; late final Box<CategoryData> box2; late final Box<SubCatData> boxsubCat2; late final Box<GroupData> boxGroup2; late final Box<Item> boxItems2;
这种写法不仅混乱,维护起来也很麻烦,肯定有更优的实现方式。请问应该采用哪种结构来满足需求?
解决方案
不需要为每个实体单独创建两个Box,更简洁高效的方式是为每个独立存储创建一个Store实例,每个Store会自动管理其内部所有实体的Box。具体实现步骤如下:
1. 初始化两个独立Store
只需要在初始化时打开两个不同名称的Store,所有实体的Adapter仅需注册一次:
late final Store store1; late final Store store2; Future<void> initStores() async { await Hive.initFlutter(); // 注册所有实体的Adapter Hive.registerAdapter(CategoryDataAdapter()); Hive.registerAdapter(SubCatDataAdapter()); Hive.registerAdapter(GroupDataAdapter()); Hive.registerAdapter(ItemAdapter()); // 打开两个独立的Store,通过名称区分存储上下文 store1 = await Hive.openStore('store_primary'); store2 = await Hive.openStore('store_secondary'); }
2. 通过Store获取对应实体的Box
使用时直接通过Store实例获取对应实体的Box,无需提前定义大量冗余的Box变量:
void operateData() { // 操作store1中的数据 final catBox1 = store1.box<CategoryData>(); final subCatBox1 = store1.box<SubCatData>(); // ... 对store1内的实体执行增删改查操作 // 操作store2中的数据 final catBox2 = store2.box<CategoryData>(); final subCatBox2 = store2.box<SubCatData>(); // ... 对store2内的实体执行增删改查操作 }
核心优势
- 结构清晰:每个Store对应一个独立存储上下文,所有实体Box归属于对应Store,避免变量冗余
- 维护便捷:新增实体时只需注册Adapter,无需为每个Store额外新增Box变量
- 关联正常:同一Store内的
ToOne/ToMany关联关系可以正常工作,不影响实体间的引用逻辑
内容的提问来源于stack exchange,提问作者Preem Palver2
相关产品推荐
相关产品推荐

