Relations Example


Let’s assume we have customers that can make multiple orders and an order can only belong to one customer. So we want each order to have a reference to the customer that made it. A simple example might look like this:

Now let’s add a customer and some orders:

To get the customer of an order:

We can also remove the relationship to a customer:


ToMany One-to-Many (1:N)

To get all the orders that a customer has made, we need to add a to-many relation to all the customers orders:

The @Backlink  annotation tells ObjectBox which ToOne relation to use to populate the list of orders. If there would be multiple to-one relations using Customer  inside the Order  class, you would need to explicitly specify the name like   @Backlink(to = "customer") .

Let’s add some orders together with a new customer. The ToMany implements the Java List interface, so we can simply add orders to it:

We can easily get the orders of a customer back by accessing the list of orders:

Removing orders works as expected:


ToMany Many-to-Many (N:M)

There is also the possibility that an entity may be referenced by not just one, but multiple other entities. For example let’s assume we have teachers that give classes to students. So obviously 🙂 students will visit classes from multiple teachers. If we want to get all teachers of a student our code may look like this:

Adding the teachers of a student works exactly like with a list:

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:


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