【发布时间】:2017-07-26 14:15:23
【问题描述】:
我目前正在玩 Room 以便将其与 Realm 进行比较,我已经对最佳处理方式有很多疑问。
在我的示例应用程序中,我有一个非常简单的模型,其中Person 可以有Cats 和Dogs。
这里是java类。
Cat 和 Dog 类继承自 Animal 类:
public abstract class RoomAnimal
{
@PrimaryKey
public int id;
public int age;
public String name;
}
Cat 类:
@Entity(tableName = "cat")
public final class RoomCat
extends RoomAnimal
{
}
Dog 类:
@Entity(tableName = "dog")
public final class RoomDog
extends RoomAnimal
{
public enum RoomColor
{
Black, White
}
public static final class RoomColorConverter
{
@TypeConverter
public RoomColor fromString(String color)
{
return color != null ? RoomColor.valueOf(color) : null;
}
@TypeConverter
public String fromRealmColor(RoomColor color)
{
return color.toString();
}
}
@TypeConverters(RoomColorConverter.class)
public RoomColor color;
}
Person 类:
@Entity(tableName = "person")
public final class RoomPerson
{
@PrimaryKey
public int id;
public String name;
}
我还有一个 POJO 来模拟用户可以养猫和狗的事实:
public final class RoomPersonWithAnimals
{
@Embedded
public RoomPerson person;
@Relation(parentColumn = "id", entityColumn = "id", entity = RoomDog.class)
public List<RoomDog> dogs;
@Relation(parentColumn = "id", entityColumn = "id", entity = RoomCat.class)
public List<RoomCat> cats;
}
问题是:如何保存RoomPersonWithAnimals对象的列表?
我不能在Dao 类中使用Insert 注释,因为RoomPersonWithAnimals 不是Entity。
对于我的RoomPersonWithAnimals 列表中的每个对象,我应该运行 3 个请求吗?
- 为了插入
person属性; - 一个为了插入
cats的列表; - 一个为了插入
dogs的列表;
提前感谢您的帮助!
【问题讨论】:
标签: android sqlite dao android-room android-components