java - Android 房间持久化库 : What is the best way to implement a many to many relation?

标签 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类(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 个请求以保存:
  • 人入 table Person
  • 猫进 table Cat
  • 它的猫进 table 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 中,可以只在一个请求中保存这些数据。是房间的限制还是我的实现有误?

    预先感谢您的帮助 !

    最佳答案

    从 Room 2.2 开始,ORM 支持表之间所有可能的关系。
    见媒体专文:Database relations with Room

    关于java - Android 房间持久化库 : What is the best way to implement a many to many relation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45368108/

    相关文章:

    java - Android MultiThread SpeedTest 存在性能问题

    android - Android 中的库可以有自己的 Intent 过滤器吗?

    android - 如何防止Service被破坏

    java - Hibernate 多对一外键默认值 0

    java - Spring MVC 和 Hibernate 集成在 intellij 中给出异常

    java - Activity 和 Fragment 之间的通信

    java - 数据库仅返回最后一个数据库项

    java - 无法加载共享库 GDX Freetype Mac

    android - Gradle 同步失败 - 将 Android Studio 更新到 3.2 后

    java - hibernate 应用程序是域驱动的吗?