Android持久性空间:"无法弄清楚如何从游标中读取此字段"

时间:2017-06-02 13:45:09

标签: android sqlite android-room android-architecture-components

我尝试使用新的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<User> loadUser();
 }

 @Dao
 public interface PetDao {
     @Query("SELECT * from Pet")
     public List<Pet> 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<UserAllPets> loadUserAndPets();
 }

我收到以下错误

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

与:

有关
 private java.util.List<?> pets;

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

1 个答案:

答案 0 :(得分:127)

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

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;
}

enter image description here

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是指嵌入式User表的id列,
  • entityColumn是指Pet表的userIdUser - Pet关系)列,
  • entity是指与Pet表格有关系的表格(User)。

4)UserDao Dao:

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

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

修改:查看我的other answer以了解多种关系。