Android Room Persistence Library:实现多对多关系的最佳方式是什么?

Android Room Persistence Library : What is the best way to implement a many to many relation?

我曾经使用过 Realm,目前正在测试 Room 以比较这两种工具。

我正在尝试实现以下多对多关系:

这是我的 Entity classes :

Person :

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

  @PrimaryKey
  public int id;

  public String name;

}

Cat class :

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

  @PrimaryKey
  public int id;

  public int age;

  public String name;

}

PersonCat class :

@Entity(tableName = "person_cat", primaryKeys = { "personId", "catId" },
    indices = { @Index(value = { "catId" }) },
    foreignKeys = { @ForeignKey(entity = RoomPerson.class, parentColumns = "id", childColumns = "personId"),
        @ForeignKey(entity = RoomCat.class, parentColumns = "id", childColumns = "catId") })
public final class RoomPersonCat {

  public int personId;

  public int catId;

  public RoomPersonCat(int personId, int catId)  {
    this.personId = personId;
    this.catId = catId;
  }

}

我还有一个 POJO,以便将养猫的人操纵到我的应用程序中:

public final class RoomPersonWithAnimals {

  @Embedded
  public RoomPerson person;

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

}

问题是:如何保存一个 List<RoomPersonWithAnimals> ?

我是不是应该每次做3个请求才能省钱:

这里是说明 3 个请求的 java 代码:

for (RoomPersonWithAnimals personWithAnimals : persons) {
  myRoomDatabase.roomPersonDao().insert(personWithAnimals.person);
  myRoomDatabase.roomCatDao().insertAll(personWithAnimals.cats.toArray(new RoomCat[personWithAnimals.cats.size()]));

  for (RoomCat cat : personWithAnimals.cats) {
    myRoomDatabase.roomPersonCatDao().insert(new RoomPersonCat(personWithAnimals.person.id, cat.id));
  }
}

在 Realm 中,可以只在一个请求中保存这些数据。是 Room 的限制还是我的实现有误?

提前感谢您的帮助!

从 Room 2.2 开始,ORM 支持表之间所有可能的关系。

请参阅 medium 上的专门文章:Database relations with Room