更新特定领域模型属性? [英] Update specific realm model properties?

查看:126
本文介绍了更新特定领域模型属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅更新某些领域模型属性,而不是尝试使用copyToRealmOrUpdate()一次又一次地保存完整的领域模型.

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)如果User已经存在于领域中,而我只想使用主键id更新name.类似于用户中的Update name only where id = "someValue".

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)因此,如果有500个领域模型并且每个领域模型中只有一个属性被更改,该怎么办.通过copyToRealmOrUpdate更新领域中的完整模型会更快还是迭代所有领域结果模型并首先查找项目然后仅更新单个属性?

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?

推荐答案

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");
        }
    });
}

您可以通过id获取托管的RealmObject,然后在事务中修改其属性.

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

这篇关于更新特定领域模型属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆