3

How to update only some realm model properties and instead of trying to save complete realm model again and again using copyToRealmOrUpdate().

public class User extends RealmObject {

@PrimaryKey
public String id = UUID.randomUUID().toString();
private String          name;
private int             age;

@Ignore
private int             sessionId;

// Standard getters & setters generated by your IDE…
public String getName() { return name; }
public void   setName(String name) { this.name = name; }
public int    getAge() { return age; }
public void   setAge(int age) { this.age = age; }
public int    getSessionId() { return sessionId; }
public void   setSessionId(int sessionId) { this.sessionId = sessionId; 
}
}

1) If User is already persisted in the realm and I only want to update name using primary key id. Something like Update name only where id = "someValue" in User.

2) So, what if there are 500 realm model and only one property of each realm model is changed. Should updating complete model in realm via copyToRealmOrUpdate will be faster or iterating all the realm results model and finding the item first and then updating the single property only?

Anurag Singh
  • 6,140
  • 2
  • 31
  • 47

2 Answers2

4
final String userId = ...;
try(Realm r = Realm.getDefaultInstance()) {
    r.executeTransaction((realm) -> {
        User user = realm.where(User.class).equalTo("id", userId).findFirst();
        if(user != null) {
            user.setName("set name");
        }
    });
}

You can obtain a managed RealmObject by id and then modify its property inside a transaction.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • Thank-you, I knew this way but I wasn't just confirmed. I thought that there could be some other way. It would be of great help if you could just answer the second part. – Anurag Singh Jun 30 '17 at 19:00
  • 1
    I'd just iterate with `for(Obj obj : realm.where(Obj.class).findAll()) { ... }` inside a transaction. I've been campaigning for a `setValue()` method for a while now but ["batch update" is still not in yet.](https://github.com/realm/realm-java/issues/762) – EpicPandaForce Jun 30 '17 at 19:05
  • This concludes the second question with first find the items and then update the relevant property in realm model within transaction block while iterating over it. Thank-you – Anurag Singh Jun 30 '17 at 19:10
2

You can change model properties inside the Transaction() if you have Created Object through Realm or get After some query on Realm database.

Now you have a instance of this class created by realm like:

Realm realm = Realm.getDefaultInstance();
User user = realm.where(User.class).equalTo("id", "your id").findFirst();// since you are serching on the basis of primary key there will be only one object

So when you want to change its property, can change into Transaction like:

realm.beginTransaction();
user.setName("abc");
realm.commitTransaction();

It will change the particular property no need to call copyToRealmOrUpdate().

OR

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
       RealmResults<User> users = realm
            .where(User.class)
            .equalTo("id", "your id")// or some other condition
            .findAll();
        for(User user : users) {
          user.setName("abc");
        }
    }
});

Hope it help!!

Ajeet Choudhary
  • 1,969
  • 1
  • 17
  • 41