I wanted to use the @Relation
annotation in an Android Project. Here I have found a description about that topic:
@Entity
public class User {
@PrimaryKey
public int id; // User id
}
@Entity
public class Pet {
@PrimaryKey
public int id; // Pet id
public int userId; // User id
public String name;
}
public class UserWithPets {
@Embedded
public User user;
@Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
public List<Pet> pets;
}
My question would be:
The parentColumn
argument is id
. But which id
is it ? Is it the id
of User
or the id
of Pet
? In the documentation it says that the parentColumn()
is a reference column in the parent POJO. But which one is the parent POJO ?
In this scenario, a relation table is created under the hood where User column is the parent and Pet column is the child. The link between them is done by the id of User which is also present in Pet as userId.
What Room is saying here is :-- "give me all the pets whose userId is matching the current id from User entity" and then it repeats it for all the ids from the User entity.
I'd refer you to this link https://medium.com/androiddevelopers/database-relations-with-room-544ab95e4542 for a better understanding of the updated concept.