我正在测试我的下一个Android应用程序的Realm db,我想做一个简单的迁移。我看到文档时有点困惑,我可以使用额外的帮助。
我有这个简单的类User:
public class User extends RealmObject {
@PrimaryKey
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
我希望在表名为“phoneNumber”的用户表中添加(通过迁移)一个附加字段。我不明白我是如何/在何处启动迁移的?我正在应用onCreate方法中创建模式,如:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.schemaVersion(0)
.migration(new MyMigration())
.build();
Realm.setDefaultConfiguration(realmConfiguration);
}
}
和我的迁移类:
public class MyMigration implements 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("User")
.addField("name", String.class)
.addField("age", int.class);
oldVersion++;
}
// Migrate to version 2: Add a primary key + object references
// Example:
// public Person extends RealmObject {
// private String name;
// @PrimaryKey
// private int age;
// private Dog favoriteDog;
// private RealmList<Dog> dogs;
// // getters and setters left out for brevity
// }
if (oldVersion == 1) {
schema.get("User")
.addField("phoneNumber", long.class, FieldAttribute.REQUIRED);
oldVersion++;
}
Log.d("MainActivity","Migration happend!");
}
}
答案 0 :(得分:1)
试试这个:
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
// DynamicRealm exposes an editable schema
RealmSchema schema = realm.getSchema();
// This is the current schema version before migration.
if (oldVersion == 0) {
schema.get("User")
.addField("phoneNumber", long.class, FieldAttribute.REQUIRED);
oldVersion++;
}
// More migrations (for version 1->2, 2->3, etc..) in the future.
}
并创建RealmConfiguration
,如下所示:
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.schemaVersion(1) // This the expected schema version after migration.
.migration(new MyMigration())
.build();
Realm.setDefaultConfiguration(realmConfiguration);