Android Realm copyToRealmOrUpdate 创建嵌套对象的副本
我有以下课程:
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对象作为响应。
让我们想象一下,每次我调用后端时,都会返回相同的三个Notes。当我获得 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 的对象内部,这些对象是重复的 - 而不是更新。
有没有办法改变这种行为?如果您需要更多信息,请告诉我。提前致谢!