Search code examples
androidrealm

Realm insert or update object with primary key


Im not sure i understand the different between them:
As I see it, realm.createObject can't really update existing key (got the error: Primary key value already exists)

OPTION 1:

    try (Realm realm = Realm.getDefaultInstance()) {
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(@NonNull Realm realm) {
                CacheFastObjTest a = realm.createObject(CacheFastObjTest.class, key);
                a.setDataType(className.getName());
                a.setExpireTimestamp(expires.getTime());
                a.setText1("dsaf");
                a.setText2("234234324");
                realm.insertOrUpdate(a);
            }
        });
    }

OPTION 2:

    try (Realm realm = Realm.getDefaultInstance()) {
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(@NonNull Realm realm) {
                CacheFastObjTest a = new CacheFastObjTest();
                a.setKey(key);
                a.setDataType(className.getName());
                a.setExpireTimestamp(expires.getTime());
                a.setText1("dsaf");
                a.setText2("234234324");
                realm.insertOrUpdate(a);
            }
        });
    }

Solution

  • I found my answer:

    In the end, the result is the same.

    Option 1 is better practice because when you use:

    realm.createObject(CacheFastObjTest.class, key);
    

    Realm is wrap your object and make sure you use the correct primary key otherwise the developer will get exceptions about it.

    In the other hand, developers can use options 2

    CacheFastObjTest a = new CacheFastObjTest();
    a.setKey(key);
    

    for the scenarios above:

    Note that Realm.createObject returns a new object with all fields set to their default values. If the object is a class with a primary key, this could create a conflict—there might be an object with that primary key set already. To avoid this, you can create an unmanaged object, set its field values, then add it to the Realm with copyToRealm or insert: Copy to clipboard.

    More information about realm with Primary key