同一类的多个领域表 [英] Multiple Realm Tables of same Class
问题描述
我有一个RealmObject类.我想要同一个类的多个表.我可以在单个Realm(数据库)中做到这一点,还是需要多个Realms(每个Realm一个表).
I have a RealmObject Class. I want multiple tables of the same class. Can I do that in a single Realm(Database) or I need to have multiple Realms(One table per each Realm).
如果必须有多个Realms,那么Realm切换过程有多快?
If it has to be multiple Realms, how fast is the Realm switching process?
推荐答案
我想要同一个类的多个表.
I want multiple tables of the same class.
那么您有两个合理的选择:
Well you have two reasonable options:
1.)添加一个鉴别符字段,该字段确定当前对象实例属于哪个表"
1.) add a discriminator field that determines which "table" this current object instance belongs to
public class MyObject extends RealmObject {
@PrimaryKey
private String tableAndId;
@Index
private String table;
@Index
private long id;
// getters, setters
}
然后您可以查询每个表":
Then you can query "per table":
RealmResults<MyObject> results = realm.where(MyObject.class)
.equalTo(MyObjectFields.TABLE, "tableA")
.findAll();
2.)使用DynamicRealm
动态创建所需的任何表,并通过RealmSchema
手动创建模式.
2.) create any table you want dynamically using DynamicRealm
and manual creation of the schema via the RealmSchema
.
DynamicRealm dynamicRealm = DynamicRealm.getInstance(config);
RealmSchema schema = dynamicRealm.getSchema();
RealmObjectSchema objectSchema;
if(!schema.contains("MyObject_Table_A")) {
objectSchema = schema.create("MyObject_Table_A");
objectSchema.addField("id", long.class, FieldAttribute.PRIMARY_KEY);
objectSchema.addField("created", Date.class, FieldAttribute.INDEXED);
//...
} else {
objectSchema = schema.get("MyObject_Table_A");
}
然后您可以写入动态领域:
And then you can write into the dynamic realm:
dynRealm.executeTransaction(new DynamicRealm.Transaction() {
@Override
public void execute(DynamicRealm dynRealm) {
DynamicRealmObject dynObj = dynRealm.where("MyObject_Table_A")
.equalTo("id", id)
.findFirst();
if(dynObj == null) {
dynObj = dynRealm.createObject("MyObject_Table_A", id);
}
dynObj.setDate("created", new Date());
}
});
每个表也可以有一个新配置,但这听起来像是一个不合理的选择,所以我什至不想提它.
You can also have a new configuration per table, but that sounds like an unreasonable option, so I barely even want to mention it.
这篇关于同一类的多个领域表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!