如何处理房间的关系?

时间:2018-01-29 09:39:24

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

我正在测试Room persistence library。我有两个entity类:

@Entity
public class User {
   @PrimaryKey
   int id;
   String name;
}

@Entity(foreignKeys = @ForeignKey(entity = User.class,
                                  parentColumns = "id",
                                  childColumns = "userId")
public class Pet {
   @PrimaryKey
   int id;
   String name;
   int userId;       
}

现在,我想获取宠物列表,并在每个Pet对象中根据User保持对userId的实际引用。因此,每次更改userId时,也应更改此引用。有可能吗?或者也许有更好的方法来处理这样的关系?

1 个答案:

答案 0 :(得分:0)

实际上,不推荐ROOM这样做。原因在于参考链接。

也许你可以尝试一下,

@Entity
public class User {
   @PrimaryKey
   int id;
   String name;
   @Embedded
   public List<Pet> userPet;
}

public class Pet {
   int id;
   String name;
}

Understand why Room doesn't allow object references

A convenience annotation which can be used in a Pojo to automatically fetch relation entities.