Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 243
Big_Chair Avatar asked Apr 24 '19 13:04

Big_Chair


2 Answers

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.

like image 69
Big_Chair Avatar answered Oct 19 '22 17:10

Big_Chair


when you use @relation, it help the DBMS (database management system) to create a tree for sorting and storing data. so when you want to run any query it is very helpful.

like image 1
Abolfazl Miadian Avatar answered Oct 19 '22 17:10

Abolfazl Miadian