Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room: How to model relationships?

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)?
like image 507
Rene Ferrari Avatar asked Sep 08 '25 16:09

Rene Ferrari


1 Answers

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)

like image 165
Devrim Avatar answered Sep 10 '25 06:09

Devrim