How to correctly migrate to Embedded Objects in Realm?

Viewed 1133

I would like to know, how to correctly migrate to Embedded Objects in Realm 10.0 update? Failed to find documentation for migration from ordinary RealmObject/RealmModel class to Embedded RealmObject/RealmModel class.

Lets say, that I have parent class and child class, which connects to parent object by id:

public class MyParent extends RealmObject {
    @PrimaryKey
    private String id;
    private MyChild child; 
    // other fields...
}
public class MyChild extends RealmObject {
    @PrimaryKey
    private String id;
    private String parentId;
    // other fields...
}

Experimentally I found, that I can:

  • either (1a) guarantee that every embedded-candidate object in MyChild's table has single parent or (1b) clear model tables
  • then (2) remove private key status from private field ("id") & remove field "id" itself from MyChild
  • (3) set embedded status to MyChild class.

In migration code it looks as follows:

realm.delete("MyParent");
realm.delete("MyChild"); // optional; variant (1b) is chosen

schema.get("MyChild")
    .removePrimaryKey()
    .removeField("id");
    
schema.get("MyChild").setEmbedded(true);

And it works. Am I right?

P.S.

1 Answers

Don't know if anyone needs this still but this is what I do.

public class MyParent extends RealmObject {
    @PrimaryKey
    private String id;
    private MyChild child; 
    // other fields...
}

@RealmClass(embedded=true)
public class MyChild extends RealmObject {
    // other fields...
}

Then in migration no need to delete object. Just remove primary key and id fields of MyChild, then

schema.get("MyChild").setEmbedded(true);
Related