【问题标题】:Android Room Persistence Library : What is the best way to implement a many to many relation?Android Room Persistence Library:实现多对多关系的最佳方法是什么?
【发布时间】:2018-01-04 04:55:59
【问题描述】:

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

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

这是我的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&lt;RoomPersonWithAnimals&gt;

我是否应该每次做 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 中,可以仅在一个请求中保存这些数据。是房间的限制还是我的实现有误?

提前感谢您的帮助!

【问题讨论】:

  • 房间很麻烦,因为它没有POJO关系。我建议根本不要这样做,或者等待他们包含类似 Realm 的设施。到目前为止,Realm 有其自身的局限性。真的让我很困扰,为什么在第一个 android 版本发布 10 年后就没有人想出一个完整的解决方案。像 CoreData 之类的东西。 Realm 的问题是它要求我们实现一个 RealmObject。 Room 的问题是它不理解 Object 内部的关系。
  • 这可能会有所帮助stackoverflow.com/a/58424784

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


【解决方案1】:

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

见媒体专文:Database relations with Room

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 2012-02-28
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2018-03-28
    相关资源
    最近更新 更多