相关疑难解决方法(0)

Android Room:使用Room插入关系实体

我在Room使用Relation添加了一对多的关系.我在这篇文章中提到了在Room中为关系编写以下代码.

该帖子告诉如何从数据库中读取值,但将实体存储到数据库中导致userId为空,这意味着两个表之间没有关系.

我不知道什么是理想的途径,insert一个UserList of Pet到数据库中,同时具有userId价值.

1)用户实体:

@Entity
public class User {
    @PrimaryKey
    public int id; // User id
}
Run Code Online (Sandbox Code Playgroud)

2)宠物实体:

@Entity
public class Pet {
    @PrimaryKey
    public int id;     // Pet id
    public int userId; // User id
    public String name;
}
Run Code Online (Sandbox Code Playgroud)

3)UserWithPets POJO:

// Note: No annotation required at this class definition.
public class UserWithPets {
   @Embedded
   public User user;

   @Relation(parentColumn = "id", …
Run Code Online (Sandbox Code Playgroud)

android android-room android-architecture-components

54
推荐指数
5
解决办法
3万
查看次数