我曾经使用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中,只能在一个请求中保存这些数据。是限制房间还是我的实施是错误的?
提前感谢您的帮助!