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

时间:2017-07-28 08:05:50

标签: java android orm android-sqlite android-room

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

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

enter image description here

这是我的Entity课程:

Person

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

  @PrimaryKey
  public int id;

  public String name;

}

Cat类:

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

  @PrimaryKey
  public int id;

  public int age;

  public String name;

}

PersonCat类:

@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次请求才能保存:

  • 该人进入表Person
  • 猫进入表Cat
  • 它的猫进入表PersonCat

这里是说明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中,只能在一个请求中保存这些数据。是限制房间还是我的实施是错误的?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

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

请参阅有关媒体的专门文章:Database relations with Room