Update specific realm model properties?

2019-08-01 19:21发布

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?

2条回答
狗以群分
2楼-- · 2019-08-01 20:07
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.

查看更多
Deceive 欺骗
3楼-- · 2019-08-01 20:08

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!!

查看更多
登录 后发表回答