Document is really confusing. Try with just below classes:
1) User Entity:
@Entity
public class User {
@PrimaryKey
public int id; // User id
}
2) Pet Entity:
@Entity
public class Pet {
@PrimaryKey
public int id; // Pet id
public int userId; // User id
public String name;
}
3) UserWithPets POJO:
// Note: No annotation required at this class definition.
public class UserWithPets {
@Embedded
public User user;
@Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
public List<Pet> pets; // or use simply 'List pets;'
/* Alternatively you can use projection to fetch a specific column (i.e. only name of the pets) from related Pet table. You can uncomment and try below;
@Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class, projection = "name")
public List<String> pets;
*/
}
parentColumn
refers to Embedded User
table's id
column,
entityColumn
refers to Pet
table's userId
(User
- Pet
relation) column,
entity
refers to table(Pet
) which has relation with User
table.
4) UserDao Dao:
@Dao
public interface UserDao {
@Query("SELECT * FROM User")
public List<UserWithPets> loadUsersWithPets();
}
Now try loadUsersWithPets()
, which returns the users with their list of pets.
Edit: See my other answer for many ot many relation.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…