Entity Inheritance

ObjectBox allows entity inheritance to share persisted properties in super classes. While ObjectBox always allowed entities to extend a non-entity base class, ObjectBox 1.4+ also allows extending entities. In addition to the @Entity  annotation, we introduced a @BaseEntity  annotation for base classes, which can be used instead of @Entity .

There three types of base classes, which are defined via annotations:

  • No annotation: The base class and its properties are not considered for persistence.
  • @BaseEntity: Properties are considered for persistence in sub classes, but the base class itself cannot be persisted.
  • @Entity: Properties are considered for persistence in sub classes, and the base class itself is a normally persisted entity.

For example:

The model for Sub, Sub_, will now include all properties: id , baseString  and subString .

It is also possible to inherit properties from another entity:

Notes on usage

  • It is possible to have classes in the inheritance chain that are not annotated with @BaseEntity. Their properties will be ignored and will not become part of the entity model.
  • It is not generally recommend to have a base entity class consisting of an ID property only. E.g. Java imposes an additional overhead to construct objects with a sub class.
  • Depending on your use case using interfaces may be more straightforward.

Restrictions

  • Superclasses annotated with @BaseEntity can not be part of a library.
  • There are no polymorphic queries (e.g. you cannot query for a base class and expect results from sub classes).
  • Currently any superclass, whether it is an @Entity or @BaseEntity, can not have any relations (like a ToOne or ToMany property).

 

Spread the love
Sign up for fresh ObjectBOX news here. No spam, just fresh developer news once in a while.
x