【问题标题】:How to save POJO with the Relation annotation in Room Peristence Library?如何使用 Room Persistence Library 中的 Relation 注释保存 POJO?
【发布时间】:2017-07-26 14:15:23
【问题描述】:

我目前正在玩 Room 以便将其与 Realm 进行比较,我已经对最佳处理方式有很多疑问。

在我的示例应用程序中,我有一个非常简单的模型,其中Person 可以有Cats 和Dogs。

这里是java类。

CatDog 类继承自 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


    【解决方案1】:

    如何保存 RoomPersonWithAnimals 对象的列表?

    至少在 1.0.0-alpha6 版本的 Room 中你不会,因为它们不是实体。

    对于我的 RoomPersonWithAnimals 列表中的每个对象,我应该播放 3 个请求吗?

    是的。您可以使用runInTransaction() 在单个 SQLite 事务中执行这三个操作。

    【讨论】:

    • 感谢您的回答。你能确认我的 POJO 是在实体之间产生一对多关系的正确方法吗?
    • @rolandl:我将其描述为“一种以原子方式检索相关实体的方式”。您不必为此使用@Relation。您可以使用runInTransaction() 并使用您想要的其他基于实体的 DAO 方法来为您的视图模型(或其他)提取内容。因此,@Relation 是一个选项,但不是必需的。
    • @CommonWare:感谢您的回答。但是我怎样才能只使用外键来产生一对多的关系呢?例如,如果我想模拟一条狗可以由几个人持有的事实。我不能将人外键添加到我的动物类中。实体可以保存外键列表吗?我在文档上没有看到这个。
    • @rolandl:“我不能将 person 外键加入我的动物类”——为什么不呢?
    • @CommonWare : 如果我这样做,如何处理狗可以被一个、两个或更多人牵着的事实?
    猜你喜欢
    • 2017-11-08
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    相关资源
    最近更新 更多