我有以下课程:
- 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 ids),然后再次调用fetchNotesAndSave(),我将得到以下结果:
- notesCount == 3;
- templatesCount == 6;
每次调用copyToRealmOrUpdate()时,与primaryKey对象内部的嵌套对象都将重复 – 不会更新.
有没有办法改变这种行为?
如果您需要更多信息,请通知我.提前致谢!
解决方法
这是因为您的Template类没有任何主键.在这种情况下,这些对象将被重新插入,因为不能保证引用的模板对象安全地被更新,即使它们是具有主键的另一个对象的一部分.
如果你添加一个@PrimaryKey到你的模板类,它应该按照你期望的方式工作.