【发布时间】:2015-12-07 19:01:23
【问题描述】:
我在 0.82.2 android 应用程序中有一个带有主键的表,其中包含以下字段:
// Each uid is generated using UUID strings:
@PrimaryKey
private String uid;
今天我已经更新到 Realm 0.86.0 以获取新的迁移 api(因为我添加了另一个表并想迁移现有用户数据)。
但是,似乎 0.82.2 领域文件中的现有数据允许主键 uid 可以为空(当我运行应用程序时,领域告诉我这一点,而没有对 uid 字段进行任何迁移。
所以,我尝试创建一个名为“id”的新主键字段,然后使用以下代码迁移非空值:
dogSchema.removePrimaryKey();
dogSchema.addField("id", String.class, FieldAttribute.PRIMARY_KEY)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
String oldUid = obj.getString("uid");
// Bring over any non null uids, generate new id to replace nulls
if (oldUid == null || oldUid.equals("")) {
// Null, so generate one as primarykey doesnt allow nulls:
String newUid = RealmUtils.generateUID();
Log.d(TAG, "### New filler dog uid = " + newUid);
obj.setString("id", newUid);
} else {
Log.d(TAG, "### Old dog uid = " + oldUid);
obj.setString("id", oldUid);
}
}
});
dogSchema.removeField("uid");
但是,迁移运行后,Realm 会抛出异常,说明:字段 'id' cant be a primaryKey as existing realm file has been contains duplicate data.尽管我可以看到每个 ID 值都不同。
如果我将 id 的 addfield 行更改为没有 PrimaryKey 属性(见下文),我会走得更远,但会遇到另一个异常,说 id 不能是主键,大概是因为我的模型有 @PrimaryKey 注释。
dogSchema.addField("id", String.class)
如何将主键迁移到 Realm 0.86.0?
【问题讨论】:
-
您的 Java RealmObject 类在迁移前后看起来如何?