How to store standard composition Classes in ObjectBox?

Viewed 109

I have Class A contains List of Class B that contains List of Class C so how I would achieve this in ObjectBox ? how do I store it?

in the pic below you can see that I have BasicInfo Class Contains Data class and so on....

I put @Entinty annotation on BasicInfo class and after generating the models class D doesn't show up in the objectbox.g.dart file as it's on of BasicInfo properties

  ModelEntity(
  id: const IdUid(1, 3501283007979667013),
  name: 'BasicInfo',
  lastPropertyId: const IdUid(1, 2073579066569957521),
  flags: 0,
  properties: <ModelProperty>[
    ModelProperty(
        id: const IdUid(1, 2073579066569957521),
        name: 'id',
        type: 6,
        flags: 1)
  ],
  relations: <ModelRelation>[],
  backlinks: <ModelBacklink>[])

enter image description here

1 Answers

If you're saying Class A contains a List of Class B, then their relationship isn't a subclass/superclass but it's a standard composition. I understand your definition looks somewhat like this:

class A {
  List<B> bs;
}

class B {
  List<C> cs;
}

class C {}

And in order to use it in ObjectBox, you can define them as relations, either a standalone ToMany relation, or a ToOne relation with a backlink - depends on what better describes your data, you can achieve the same with both.

1st alternative - using ToMany

ToMany relation stores the info in a separate "table" of IDs, like: A.id <--> B.id and another one between B.id <--> C.id.

@Entity()
class A {
  int id;
  final bs = ToMany<B>();
}

@Entity()
class B {
  int id;
  final cs = ToMany<C>;
}

@Entity()
class C {
  int id;
}

2nd alternative - using ToOne with a backlink

ToOne relation can achieve the same in your case and the relatin info is actually stored on the object itself as a single ID, i.e. there's a hidden int B.classAId field that and you can get all Bs for a class A instance by looking for those Bs pointing to this A. This is done behind the scenes by a ToMany<> with a Backlink() annotation.

@Entity()
class A {
  int id;

  @Backlink()
  final bs = ToMany<B>();
}

@Entity()
class B {
  int id;
 
  final a = ToOne<A>; 

  @Backlink()
  final cs = ToMany<C>;
}

@Entity()
class C {
  int id;

  final b = ToOne<B>; 
}
Related