In Realm Android 3.4.0-SNAPSHOT, support for queries across backlinks got merged, and with the next release, inverse relations will be out of beta.

This allows us to simplify the Realm schema by replacing many bi-directional links with uni-directional ones, and replace the links “pointing back” with backlinks.

@LinkingObjects

The support for inverse relations was initially added in 3.1.0, but it didn’t support queries across them until now. This essentially means that for any relation you have in your schema (either 0..1 or 0..* ), you can now see the objects that are linking to your current object.

For example, we have the following model classes:

And what we want to specify is that a Person can have multiple dogs. Let’s say that a Dog can only be owned by one person. Previously, you would have to create the following schema:

And while a Dog is technically owned by a Person, we don’t really need to say that a “Dog belongs to a Person”, right?

We say the Person owns the Dog. Then we implicitly know that the Dog is owned by that given Person.

This is an inverse relationship: if a Person owns a Dog, then that Dog is owned by that Person.

We can now replace manually established bi-directional links, with automatically managed backlinks to linking objects.

Every relationship, either 0..1 or 0..* creates their corresponding backlinks in the target class.

One thing to note is that an inverse relationship can only be seen as 0..* meaning it must be declared as RealmResults<T> . Also, when declared, it is final and the accessors are transformed to return the managed linking objects.

With that, we no longer need to manually manage the owners of the Dog, it’s managed by Realm automatically :)

What’s worth a mention is that backlink fields don’t need to be added with migration, but if you remove the list or property that points back, then of course a migration is needed to remove that field.

Conclusion