Android Persistence room:“无法弄清楚如何从游标中读取此字段”

我正在尝试使用新的Android Persistence Room Library在两个数据库表之间创建关系。 我查看了文档,并尝试实现https://developer.android.com/reference/android/arch/persistence/room/Relation.html上的示例:

@Entity public class User { @PrimaryKey int id; } @Entity public class Pet { @PrimaryKey int id; int userId; String name; } @Dao public interface UserDao { @Query("SELECT * from User") public List loadUser(); } @Dao public interface PetDao { @Query("SELECT * from Pet") public List loadUserAndPets(); } public class UserAllPets { @Embedded public User user; @Relation(parentColumn = "user.id", entityColumn = "userId", entity = Pet.class) public List pets; } @Dao public interface UserPetDao { @Query("SELECT * from User") public List loadUserAndPets(); } 

我收到以下错误

  ...error: Cannot figure out how to read this field from a cursor. 

和—关联:

  private java.util.List pets; 

我想指出,我发现他们的文档中的一些内容确实令人困惑。 例如缺少@PrimaryKey以及User类缺少@Entity注释的事实,尽管它应该是一个实体(就像我看到的那样)。 有没有人遇到同样的问题? 非常感谢提前

文件真的令人困惑。 试试下面的课程:

1)用户实体:

 @Entity public class User { @PrimaryKey public int id; // User id } 

2)宠物实体:

 @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 pets; // or use simply 'List pets;' /* Alternatively you can use projection to fetch a specific column (ie 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 pets; */ } 
  • parentColumn是指Embedded User表的id列,
  • entityColumn引用Pet表的userIdUserPet关系)列,
  • entity指的是与User表有关系的表( Pet )。

4)UserDao Dao:

 @Dao public interface UserDao { @Query("SELECT * FROM User") public List loadUsersWithPets(); } 

现在尝试loadUsersWithPets() ,它返回用户的宠物列表。

编辑:看到我的其他答案很多很多关系。