更改领域字段的数据类型-Java [英] Change datatype of Realm field - Java
问题描述
我想将Realm字段的数据类型从String
更改为int
,仅供参考,该字段也是Primary Key
.我在RealmMigration
中找不到解决此问题的方法.
I would like to change the data type of a Realm field from String
to int
and FYI the field is also a Primary Key
. I couldn't find a method in RealmMigration
to solve this issue.
PS:我的应用程序已经投入生产,并且该字段中当前所有的值都是整数.
PS : My app is already in production and all the values that are currently in that field are integers.
编辑1
我的模型课
public class Team extends RealmObject {
@SerializedName("id")
@PrimaryKey
private int id;
@SerializedName("name")
private String name;
@SerializedName("description")
private String description;
}
尝试克里斯蒂安的回答后我的移民
my migration after trying Christian's answer
if (oldVersion == 6) {
RealmObjectSchema teamSchema = schema.get("Team");
teamSchema.addField("temp_id", int.class)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.setInt("temp_id", Integer.valueOf(obj.getString("id")));
}
})
.removeField("id")
.renameField("temp_id", "id")
.addPrimaryKey("id");
}
推荐答案
没有单线方法,但是您可以遵循与迁移示例相同的模式: https://github.com/realm/realm-java/blob/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample/model/Migration.java#L132-L132
There isn't an one-liner method, but you can follow the same pattern as in our Migration example: https://github.com/realm/realm-java/blob/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample/model/Migration.java#L132-L132
schema.get("MyClass")
.addField("new_key", int.class)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.setInt("new_key", Integer.valueOf(obj.getString("old_key")));
}
})
.removeField("old_key")
.addPrimaryKey("new_key")
.renameField("new_key", "old_key");
这篇关于更改领域字段的数据类型-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!