Relations
ObjectBox Relations: Learn how to create and update to-one and to-many relations between entities in ObjectBox and improve performance.
ObjectBox - Relations
Prefer to dive right into code? Check out our
Kotlin Android example app using relations,
Java relations playground Android app,
The Python API does not yet support relations.
Objects may reference other objects, for example using a simple reference or a list of objects. In database terms, we call those references relations. The object defining a relation we call the source object, the referenced object we call the target object. So a relation has a direction.
If there is one target object, we call the relation to-one. And if there can be multiple target objects, we call it to-many. Relations are lazily initialized: the actual target objects are fetched from the database when they are first accessed. Once the target objects are fetched, they are cached for further accesses.
To-One Relations
You define a to-one relation using the ToOne
class, a smart proxy to the target object. It gets and caches the target object transparently. For example, an order is typically made by one customer. Thus, we could model the Order
class to have a to-one relation to the Customer
like this:
Now let’s add a customer and some orders. To set the related customer object, call setTarget()
(or assign target
in Kotlin) on the ToOne instance and put the order object:
If the customer object does not yet exist in the database (i.e. its ID is zero), ToOne
will put it (so there will be two puts, one for Order
, one for Customer
). If it already exists, ToOne
will only create the relation (so there's only one put for Order
, as explicitly written in the code). See further below for details about updating relations.
Note: if your related entity uses self-assigned IDs with @Id(assignable = true)
ObjectBox won't know if a target object is a new one or an existing one, therefore it will NOT insert it, you would have to call customerBox.put(customer)
manually (considering the previous example). See below about updating ToOne for details.
Have a look at the following code how you can get (read) the customer of an order:
This will do a database call on the first access (lazy loading). It uses lookup by ID, which is very fast in ObjectBox. If you only need the ID instead of the whole target object, you can completely avoid this database operation because it's already loaded: use order.customer.targetId/getTargetId()
.
We can also remove the relationship to a customer:
Note that this does not remove the customer from the database, it just dissolves the relationship.
How ToOne works behind the scenes
If you look at your model in objectbox-models/default.json
(or lib/bjectbox-model.json
in Dart) you can see, a ToOne property is not actually stored. Instead, the ID of the target object is saved in a virtual property named like the ToOne property appended with Id.
Expose the ToOne target ID property
Only Java/Kotlin
You can directly access the target ID property by defining a long
(or Long
in Kotlin) property in your entity class with the expected name:
You can change the name of the expected target ID property by adding the @TargetIdProperty(String) annotation to a ToOne.
Initialization Magic
Only Java/Kotlin
Did you notice that the ToOne
field customer
was never initialized in the code example above? Why can the code still use customer
without any NullPointerException? Because the field actually is initialized – the initialization code just is not visible in your sources.
The ObjectBox Gradle plugin will transform your entity class (supported for Android projects and Java JVM projects) to do the proper initialization in constructors before your code is executed. Thus, even in your constructor code, you can just assume ToOne
and ToMany
/ List
properties have been initialized and are ready for you to use.
If your setup does not support transformations, currently Kotlin JVM (Linux, macOS, Windows) projects, add the below modifications yourself. You also will have to call box.attach(entity)
before modifying ToOne or ToMany properties.
Improve Performance
Only Java/Kotlin
To improve performance when ObjectBox constructs your entities, you should provide an all-properties constructor.
For a ToOne you have to add an id parameter, typically named like the ToOne field appended with Id
. Check your objectbox-models/default.json
file to find the correct name.
An example:
To-Many Relations
To define a to-many relation, you can use a property of type ToMany
. As the ToOne class, the ToMany
class helps you to keep track of changes and to apply them to the database.
Note that to-many relations are resolved lazily on first access, and then cached in the source entity inside the ToMany
object. So subsequent calls to any method, like size()
of the ToMany
, do not query the database, even if the relation was changed elsewhere. To get the latest data fetch the source entity again or call reset()
on the ToMany
.
There is a slight difference if you require a one-to-many (1:N) or many-to-many (N:M) relation. A 1:N relation is like the example above where a customer can have multiple orders, but an order is only associated with a single customer. An example for an N:M relation is students and teachers: students can have classes by several teachers but a teacher can also instruct several students.
One-to-Many (1:N)
To define a one-to-many relation, you need to annotate your relation property with @Backlink
. It links back to a to-one relation in the target object. Using the customer and orders example, we can modify the customer class to have a to-many relation to the customer's orders:
When using @Backlink
it is recommended to explicitly specify the linked to relation using to
. It is possible to omit this if there is only one matching relation. However, it helps with code readability and avoids a compile-time error if at any point another matching relation is added (in the above case, if another ToOne<Customer>
is added to the Order class).
Let’s add some orders together with a new customer. ToMany
implements the Java List interface, so we can simply add orders to it:
If the order entities do not yet exist in the database, ToMany
will put them. If they already exist, it will only create the relation (but not put them). See further below for details about updating relations.
Note: if your entities use self-assigned IDs with @Id(assignable = true)
the above will not work. See below about updating ToMany for details.
We can easily get the orders of a customer back by accessing the list of orders:
Removing orders from the relation works as expected:
Many-to-Many (N:M)
To define a many-to-many relation you simply add a property using the ToMany
class. Assuming a students and teachers example, this is how a simple student class that has a to-many relation to teachers can look like:
Adding the teachers of a student works exactly like with a list:
If the teacher entities do not yet exist in the database, ToMany
will also put them. If they already exist, ToMany
will only create the relation (but not put them). See further below for details about updating relations.
Note: if your entities use self-assigned IDs with @Id(assignable = true)
the above will not work. See below about updating ToMany for details.
To get the teachers of a student we just access the list:
And if a student drops out of a class, we can remove a teacher from the relation:
Access Many-To-Many in the reverse direction
Following the above example, you might want an easy way to find out what students a teacher has. Instead of having to perform a query, you can just add a to-many relation to the teacher and annotate it with the @Backlink
annotation:
Using the List interface for to-many
Only for Java/Kotlin
Instead of the ToMany
type it is also possible to use List
(or MutableList
in Kotlin) for a to-many property. At runtime the property will still be a ToMany
instance (ToMany
does implement the List
interface) due to the initialization magic described above, or if manually initialized as seen in the example below.
This may be helpful when trying to deserialize an object that contains a to-many from JSON. However, note that if the JSON deserializer replaces the ToMany
instance with e.g. an ArrayList
during put the to-many property is skipped. It is then up to you to create the relation.
Updating Relations
The ToOne and ToMany relation classes assist you to persist the relation state. They keep track of changes and apply them to the database once you put the Object containing them. ObjectBox supports relation updates for new (not yet persisted; ID == 0) and existing (persisted before; ID != 0) Objects.
For convenience, ToOne and ToMany will put Objects added to them if they do not yet exist (ID == 0). If they already exist (their ID != 0, or you are using @Id(assignable = true)
), only the relation will be created or destroyed (internally the Object ID is added to or removed from the relation). In that case, to put changes to the properties of related Objects use their specific Box instead:
Updating ToOne
The ToOne class offers the following methods to update the relation:
setTarget(target)
makes the given (new or existing) Object the new relation target; passnull
to clear the relation.setTargetId(targetId)
sets the relation target based on the given ID of an existing Object; pass0
(zero) to clear the relation.Java/Kotlin only:
setAndPutTarget(target)
makes the given (new or existing) Object the new relation target and puts the owning, source Object and if needed the target Object.
Note: attach the Box before calling setAndPutTarget()
on a new (not put) Object owning a ToOne:
Note: if the target Object uses self-assigned IDs with @Id(assignable = true)
it will not be put when the Object that owns the relation is put:
This is because ObjectBox only puts related entities with an ID of 0. See the documentation about IDs for background information.
Updating ToMany
The ToMany
relation class is based on a standard List
with added change tracking for Objects. As mentioned above, it will put new Objects (ID == 0) that are added to it once the Object owning it is put. And when removing Objects from it, just the relation is cleared, the Objects are not removed from their Box.
See the documentation on One-to-Many and Many-to-Many above for details.
Note (Java/Kotlin only): if your entities are using self-assigned IDs with @Id(assignable = true)
additional steps are required. Read on for details:
If the owning, source Object uses @Id(assignable = true)
attach its Box before modifying its ToMany:
If the target Object, like Order
above, is using self-assigned IDs put the target Objects before adding them to the ToMany relation:
The above steps are required because, when putting the Object owning the ToMany only the relation is updated. This is because ObjectBox only puts target Objects with an ID of 0. See the documentation about IDs for the background information.
Example: Extending the Model with an Address
A typical extension to the customer/order example we have started earlier would be to add an Address
type. While you could model street, ZIP and so on directly into Customer
, it usually makes sense to normalize that out into a separate entity. And when you think about the usual shopping sites, they all let you have multiple addresses...
So, typically, this is how you would model that:
an address is bound to a customer; add a
ToOne<Customer> customer
toAddress
an order is shipped to one address, and might have a diverging billing address optionally; add
ToOne<Address> shippingAddress
andToOne<Address> billingAddress
toOrder
For each
ToOne
you could have a matchingToMany
on the other side of the relation (backlink)
Example: Modelling Tree Relations
You can model a tree relation with a to-one and a to-many relation pointing to itself:
This lets you navigate a tree nodes parent and children:
Last updated