• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

java - 使用新模式的 Realm 迁移

[复制链接]
菜鸟教程小白 发表于 2022-12-9 06:48:00 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我有一个已经使用 Realm 数据库的应用程序。我现在想向架构中添加一个新的 RealmObject(比如我想添加 Person 作为我的新 RealmObject 类)。从文档看来,我需要执行以下操作才能完成这项工作:

RealmConfiguration config = new RealmConfiguration.Builder()
.schemaVersion(1) // Must be bumped when the schema changes
.migration(new MyMigration()) // Migration to run instead of throwing an exception
.build()




// Example migration adding a new class
class MyMigration extends RealmMigration {

  @Override
  public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
       // DynamicRealm exposes an editable schema
       RealmSchema schema = realm.getSchema();

       // Migrate to version 1: Add a new class.
       // Example:
       // public Person extends RealmObject {
       //     private String name;
       //     private int age;
       //     // getters and setters left out for brevity
       // }
       if (oldVersion == 0) {
          schema.create("erson")
              .addField("name", String.class)
              .addField("age", int.class);
          oldVersion++;
       }
       etc.... 

我的问题是:我们真的需要在这里“手动”创建 Person 模式(即添加字段及其类型)吗?或者有没有办法使用 Person RealmObject,因为我们已经定义了哪些字段应该属于那里的新类



Best Answer-推荐答案


My question here: do we really need to create the Person schema "by hand" (i.e. add the fields, with their type) here?

是的。

Or is there a way to use the Person RealmObject since we have already defined what fields should belong to the new class there

我实际上和 Christian Melchior 谈过这个 here ,但问题使用当前存在的 RealmModel 类来定义需要添加的字段和需要删除的字段是:

如果您进行了复杂的迁移(涉及 renameField()transform() 操作),则无法保证您从对象的 V5 定义的操作如果您将迁移基于稍后在模式版本 V8 中拥有的 Realm 模型,则仍然可以执行到 V6 的对象。

这实质上意味着考虑到 RealmModel 可能会发生变化,仅仅“更新到最新模型”甚至可能导致数据丢失,您将引用不存在的字段等等。

基本上,使用当前版本的 Realm 模型来定义架构修改操作并不是面向 future 的。

关于java - 使用新模式的 Realm 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45717975/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap