Links allow you to express relationships between objects — such as the author (User) of a Comment, or the Post the comment belongs to.
IsarLink<T> can contain zero or one related objects so it can be used to express a to-one relationship.
IsarLink has a single property called
value which holds the linked object.
Links are lazy so you need to explicitly tell the
IsarLink to load or save the
value. You can do this by calling
Let's start by adding an IsarLink to a collection:
We defined a link between teachers and students. Every student can have exactly one teacher in this example.
First we create a math teacher, then we assign it to a student. As you can see in this example, we have to
put() the student manually (obviously) but the isar link takes care of inserting the teacher.
It would make more sense if the student from the previous example could have multiple teachers. Fortunately Isar has
IsarLinks<T> which can contain multiple related objects and express a to-many relationship.
Set<T> so it exposes all the methods that are allowed for sets.
IsarLinks behaves much like
IsarLink and is also lazy. To load all linked object call
linkProperty.load(). To persist the changes call
IsarLinks are represented in the same way. This allows us to upgrade the
IsarLink<Teacher> from before to an
IsarLinks<Teacher> to assign multiple teachers to a single student.
This works because we did not change the name of the link (
teachers) so Isar remembers it from before.
I hear you ask "What if we want to express reverse relationships?". Don't worry, we'll now introduce backlinks.
Backlinks are links in reverse direction. Each link always has an implicit backlink. You can make it available to your app by annotating an
Backlinks do not require additional memory or resources and you can freely add, remove and rename them without loosing data.
We want to know which students a specific teacher has so we define a backlink:
We need to specify the link to which the backlink points. It is possible to have multiple different links between two objects.
IsarLinks both have a zero-arg constructor which should be used to assign the link property when the object is created. It is good practice to make link properties
put() your object for the first time, the link gets initialized with source and target collection and you can call methods like
It is illegal to move a link to another object and will lead to undefined behavior.