gpt4 book ai didi

Android Persistence room : "Cannot figure out how to read this field from a cursor"

转载 作者:IT老高 更新时间:2023-10-28 21:56:41 26 4
gpt4 key购买 nike

我正在尝试使用新的 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 注释这一事实,尽管它应该是一个实体(据我所知)。有人遇到同样的问题吗?提前非常感谢

最佳答案

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 表的userId(User - Pet 关系)列,
  • entity 是指与User 表有关系的表(Pet)。

4) UserDao 道:

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

现在试试 loadUsersWithPets(),它会返回用户及其宠物列表。

编辑:见我的other answer对于很多很多关系。

关于Android Persistence room : "Cannot figure out how to read this field from a cursor",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44330452/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com