【发布时间】: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<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 中,可以仅在一个请求中保存这些数据。是房间的限制还是我的实现有误?
提前感谢您的帮助!
【问题讨论】:
-
房间很麻烦,因为它没有POJO关系。我建议根本不要这样做,或者等待他们包含类似 Realm 的设施。到目前为止,Realm 有其自身的局限性。真的让我很困扰,为什么在第一个 android 版本发布 10 年后就没有人想出一个完整的解决方案。像 CoreData 之类的东西。 Realm 的问题是它要求我们实现一个 RealmObject。 Room 的问题是它不理解 Object 内部的关系。
-
这可能会有所帮助stackoverflow.com/a/58424784
标签: java android orm android-sqlite android-room