Reputation: 993
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).
If it has to be multiple Realms, how fast is the Realm switching process?
Upvotes: 3
Views: 2645
Reputation: 81588
I want multiple tables of the same class.
Well you have two reasonable options:
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.) 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.
Upvotes: 2