如何在 Room Persistence Library 中保存带有 Relation 注解的 POJO?

How to save POJO with the Relation annotation in Room Peristence Library?

我目前正在玩 Room,以便将它与 Realm 进行比较,我已经对做事情的最佳方式有很多疑问。

在我的示例应用程序中,我有一个非常简单的模型,其中一个 Person 可以有 Cats 和 Dogs。

这里是 java classes.

CatDog class 继承自 Animal class :

public abstract class RoomAnimal
{

  @PrimaryKey
  public int id;

  public int age;

  public String name;

}

Cat class :

@Entity(tableName = "cat")
public final class RoomCat
    extends RoomAnimal
{

}

Dog class :

@Entity(tableName = "dog")
public final class RoomDog
    extends RoomAnimal
{

  public enum RoomColor
  {
    Black, White
  }

  public static final class RoomColorConverter
  {

    @TypeConverter
    public RoomColor fromString(String color)
    {
      return color != null ? RoomColor.valueOf(color) : null;
    }

    @TypeConverter
    public String fromRealmColor(RoomColor color)
    {
      return color.toString();
    }

  }

  @TypeConverters(RoomColorConverter.class)
  public RoomColor color;

}

Person class :

@Entity(tableName = "person")
public final class RoomPerson
{

  @PrimaryKey
  public int id;

  public String name;

}

我还有一个 POJO 来模拟用户可以养猫养狗的事实:

public final class RoomPersonWithAnimals
{

  @Embedded
  public RoomPerson person;

  @Relation(parentColumn = "id", entityColumn = "id", entity = RoomDog.class)
  public List<RoomDog> dogs;

  @Relation(parentColumn = "id", entityColumn = "id", entity = RoomCat.class)
  public List<RoomCat> cats;

}

问题是:如何保存 RoomPersonWithAnimals 个对象的列表?

我不能在 Dao class 中使用 Insert 注释,因为 RoomPersonWithAnimals 不是 Entity.

对于 RoomPersonWithAnimals 列表中的每个对象,我应该 运行 3 个请求吗?

提前感谢您的帮助!

how to save a list of RoomPersonWithAnimals objects ?

你不需要,至少在 1.0.0-alpha6 版本的 Room 中,因为它们不是实体。

For each objects of my list of RoomPersonWithAnimals should I play 3 requests ?

是的。您可以使用 runInTransaction() 在单个 SQLite 事务中执行这三个操作。