ObjectBox Database Relations

To-One Relations

The @Relation annotation defines a relation to another object. Apply it to the property holding the other entity object.

ObjectBox uses an additional property to reference the ID of the target entity. This property is automatically created if it does not exist. The generated property will be named like the @Relation property with an “Id” postfix.

The getter-methods of relations (in this example getCustomer()) resolve the target entity lazily on their first call. Subsequent calls will return the previously resolved object immediately.

Note that if you change the ID property (here customerId), the next call to the getter ( getCustomer()) will resolve the entity for the updated ID.

Also, if you set a new entity ( setCustomer()), the ID property ( customerId) will be updated as well.

To-Many Relations

@Relation can also be applied to a property that is a List of target entities. Currently, this must be the back link of a to-one @Relation as we saw above. This might require you to set up the to-one @Relation first. Future versions of ObjectBox may drop this requirement.

To define a to-many relation as the back link to a to-one relation, you need to specify the ID property of the to-one relation. Note that this ID property is part of the target entity (to-one), and not the entity of the to-many relation.

Using the example from above we extend it with a to-many relation “orders” in “Customer”:

To-many relations are resolved lazily on the first request, and then cached in the source entity inside a List object. So subsequent calls to the get method of the relation do not query the database.

Updating Relations

Note: the following section represents the status quo of the beta version. We will likely simplify the process for the 1.0 release.

Updating to-many relations requires some additional work. Because to-many lists are cached, they are not updated when related entities are added to the database. The following code illustrates the behavior:

So to add new related entities, add them manually to the to-many list of the source entity:

Likewise, you can delete related entities:

When adding, updating or removing many related entities you can use the reset method to clear the list of cached entities. The next get will then requery the related entities:

Example: Modelling Tree Relations

You can model a tree relation with two @Relation annotations (a to-one and a to-many relation) pointing to itself:

The generated entity lets you navigate its parent and children:

Spread the love