Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly migrate to Embedded Objects in Realm?

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.

  • Info & examples about PR for Embedded Objects: https://github.com/realm/realm-java/pull/6730
  • Embedded Objects documentation: https://docs.mongodb.com/realm/android/embedded-objects/
like image 916
Dan Savelyev Avatar asked Nov 22 '25 07:11

Dan Savelyev


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);
like image 65
thunderson Avatar answered Nov 24 '25 22:11

thunderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!