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 EmbeddedUser
table’sid
column,entityColumn
refers toPet
table’suserId
(User
–Pet
relation) column,entity
refers to table(Pet
) which has relation withUser
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.