我曾经使用 Realm,目前正在测试 Room 以比较这两种工具。
我正在尝试实现以下多对多关系:
这是我的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 个请求以保存:
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 中,可以只在一个请求中保存这些数据。是房间的限制还是我的实现有误?
预先感谢您的帮助 !
最佳答案
从 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/