Search code examples
androidandroid-sqliteandroid-room

Room - Why use @Relation over @ForeignKey?


My current goal is to have a one-to-many relation in my data.

From various tutorials I've come to understand that I have two main ways of doing this.

  1. Create two entities and have the child use the @ForeignKey annotation

  2. Create these two entities and an extra POJO, which uses @Embedded for the parent entity and @Relation to have a list of children tied to the parent

So, using Relation just seems like extra effort. Or am I missing something?
Is the big advantage of Relation this:

When the Pojo is returned from a query, all of its relations are also fetched by Room.

Which would not be as easy with the first method?


Solution

  • From Gautam's comment and further reading I now understand it this way:
    @Relation is a convenience option to make retrieving connected entities easier. The price for this convenience is to give up the ability to control what happens on parent entry deletion and possibly other things.