我有一个已经使用 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-推荐答案 strong>
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/
|