[英]Android Room Persistence Library : What is the best way to implement a many to many relation?
I used to use Realm and I am currently testing Room in order to compare both tools.我曾经使用过 Realm,目前正在测试 Room 以比较这两种工具。
I am trying to implement the following many to many relation:我正在尝试实现以下多对多关系:
Here my Entity
classes:这是我的
Entity
类:
The Person
: Person
:
@Entity(tableName = "person")
public final class RoomPerson {
@PrimaryKey
public int id;
public String name;
}
The Cat
class: Cat
类:
@Entity(tableName = "cat")
public final class RoomCat {
@PrimaryKey
public int id;
public int age;
public String name;
}
And the PersonCat
class:和
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;
}
}
I also have a POJO in order to manipulate a person with cats into my app:我还有一个 POJO,以便将养猫的人操纵到我的应用程序中:
public final class RoomPersonWithAnimals {
@Embedded
public RoomPerson person;
@Relation(parentColumn = "id", entityColumn = "id", entity = RoomCat.class)
public List<RoomCat> cats;
}
The question is: how to save a List<RoomPersonWithAnimals>
?问题是:如何保存
List<RoomPersonWithAnimals>
?
Should I do 3 requests each time in order to save:我应该每次做 3 个请求以保存:
Person
Person
Cat
Cat
PersonCat
PersonCat
Here the java code that illustrate the 3 requests:这里是说明 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));
}
}
In Realm, it's possible to save in only one request these data.在 Realm 中,可以只在一个请求中保存这些数据。 Is is a limitation of Room or my implementation is wrong?
是 Room 的限制还是我的实现有误?
Thank you in advance for your help !预先感谢您的帮助 !
Since Room 2.2, the ORM support all possible relations between tables.从 Room 2.2 开始,ORM 支持表之间所有可能的关系。
See the dedicated article on medium: Database relations with Room参见 medium 的专题文章: Database relations with Room
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.