我有以下类(class):
public class Note extends RealmObject {
@PrimaryKey
private String id;
private Template template;
// other primitive fields, getters & setters
}
public class Template extends RealmObject {
private String name;
private String color;
// other primitive fields, getters & setters
}
我通过 Retrofit 和 Gson 从后端获取数据,因此我有现成的 java 对象作为响应。
假设后端每次调用它时都会返回相同的三个注释。 当我获得 Note 对象列表时,我会执行以下操作:
private void fetchNotesAndSave() {
List<Notes> notes = getNotesViaRetrofit();
Realm realm = Realm.getInstance(mContext);
realm.beginTransaction();
realm.copyToRealmOrUpdate(notes);
realm.commitTransaction();
realm.close();
}
之后我调用这些行来检查存储对象的数量:
int notesCount = mRealm.where(Note.class).findAll().size();
int templatesCount = mRealm.where(Template.class).findAll().size();
第一次:
notesCount == 3;
templatesCount == 3;
没错。但是,如果我再次调用服务器,获取相同的笔记(相同的 primaryKey id),并再次调用 fetchNotesAndSave(),我将得到以下结果:
notesCount == 3;
templatesCount == 6;
每次我调用 copyToRealmOrUpdate() 时,具有 primaryKey 的对象内部的嵌套对象都会重复 - 不会更新。
有没有办法改变这种行为? 如果您需要更多信息,请告诉我。提前致谢!
最佳答案
这是因为您的 Template 类没有任何主键。在这种情况下,这些对象会再次插入,因为不能保证引用的模板对象可以安全地更新,即使它们是另一个具有主键的对象的一部分。
如果您将 @PrimaryKey
添加到您的模板类中,它应该可以按照您的预期工作。
关于java - Android Realm copyToRealmOrUpdate 创建嵌套对象的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30258351/