【问题标题】:How to correctly migrate to Embedded Objects in Realm?如何正确迁移到 Realm 中的嵌入式对象?
【发布时间】:2020-10-22 13:04:36
【问题描述】:

我想知道,如何正确迁移到 Realm 10.0 更新中的嵌入式对象?找不到从普通 RealmObject/RealmModel 类迁移到 Embedded RealmObject/RealmModel 类的文档。

假设我有父类和子类,它们通过 id 连接到父对象:

public class MyParent extends RealmObject {
    @PrimaryKey
    private String id;
    private MyChild child; 
    // other fields...
}
public class MyChild extends RealmObject {
    @PrimaryKey
    private String id;
    private String parentId;
    // other fields...
}

通过实验我发现,我可以:

  • 任一 (1a) 保证每个嵌入的候选对象 MyChild 的表有单亲或 (1b) 明确的模型表
  • 然后 (2) 从私有字段 ("id") 中删除私钥状态并删除字段 来自 MyChild 的“id”本身
  • (3) 将嵌入状态设置为 MyChild 类。

在迁移代码中如下所示:

realm.delete("MyParent");
realm.delete("MyChild"); // optional; variant (1b) is chosen

schema.get("MyChild")
    .removePrimaryKey()
    .removeField("id");
    
schema.get("MyChild").setEmbedded(true);

而且它有效。 我说的对吗?

附言

【问题讨论】:

    标签: java android realm


    【解决方案1】:

    不知道是否还有人需要这个,但我就是这样做的。

    public class MyParent extends RealmObject {
        @PrimaryKey
        private String id;
        private MyChild child; 
        // other fields...
    }
    
    @RealmClass(embedded=true)
    public class MyChild extends RealmObject {
        // other fields...
    }
    

    然后在迁移中不需要删除对象。只需删除 MyChild 的 主键 和 id 字段,然后

    schema.get("MyChild").setEmbedded(true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多