Android Room: How to model relationships?

Rene Ferrari picture Rene Ferrari · May 19, 2017 · Viewed 25.9k times · Source

I have just started working with Room and although everything seems to be pretty intuitive I currently don't really understand how exactly I could handle relationships.

Because SQLite is a relational database, you can specify relationships between objects. Even though most ORM libraries allow entity objects to reference each other, Room explicitly forbids this. Even though you cannot use direct relationships, Room still allows you to define Foreign Key constraints between entities.(Source: https://developer.android.com/topic/libraries/architecture/room.html#no-object-references)

  1. How should you model a Many to Many or One to Many Relationship?
  2. What would this look like in practice (example DAOs + Entities)?

Answer

Devrim picture Devrim · Jun 8, 2017

You can use @Relation annotation to handle relations at Room.

A convenience annotation which can be used in a Pojo to automatically fetch relation entities. When the Pojo is returned from a query, all of its relations are also fetched by Room.

See document.

(Google's document has confusing examples. I have written the steps and some basic explanation at my another answer. You can check it out)