[英]How to partially update a realm object
How do I update a realm object partially? 如何部分更新领域对象?
Imagine I have a model like this: 想象一下,我有一个这样的模型:
class Person {
@PrimaryKey long id;
String name;
Address address;
}
Let's assume I sync my local realm database with a backend and the backend gives me only a Person
with id
and name
where the name has changed (no address). 假设我将本地域数据库与后端同步,后端只给我一个名称已更改的id
和name
的Person
(没有地址)。
How do I update only the Person.name
? 如何仅更新Person.name
? Furthermore, I want Person.address
stay as it is in the local database. 此外,我希望Person.address
保持原样在本地数据库中。
You can only insert/copy/update entire objects, you can't specify "what fields you don't want to save". 您只能插入/复制/更新整个对象,不能指定“您不想保存的字段”。 So you should query your object and set its stuff and then save it back. 所以你应该查询你的对象并设置它的东西,然后保存回来。
final Address address = getAddress();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Person person = realm.where(Person.class).equalTo(PersonFields.ID, id).findFirst();
if(person == null) {
person = new Person(); // or realm.createObject(Person.class, id);
person.id = id;
}
person.address = address;
realm.insertOrUpdate(person);
}
});
To update the Person.name
you need to first query the Person
object and then update its name
. 要更新Person.name
您需要先查询Person
对象,然后更新其name
。 All other fields will remain unchanged: 所有其他字段将保持不变:
long id = ... // from backend
String newName = ... // from backend
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
Person person = realm.where(Person.class).equalTo("id", id).findFirst();
person.setName(newName);
realm.commitTransaction();
realm.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.