【发布时间】:2015-05-15 11:27:00
【问题描述】:
我有以下课程:
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 的对象内部的嵌套对象都会重复 - 不会更新。
有没有办法改变这种行为? 如果您需要更多信息,请告诉我。提前致谢!
【问题讨论】: