我有2个班级:
public class DbFile extends RealmObject {
@PrimaryKey
private String fileId;
// getters and setters
}
public class DbNews extends RealmObject {
@PrimaryKey
private long newsId;
private RealmList<DbFile> photos;
// getters and setters
}
当用户从服务器提取数据时,我想创建一个新的DbNews实体(如果不存在),或者更新现有实体。
public void addNews(ApiNews news) {
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(r -> {
DbNews inDb = newsById(news.getId());
if (inDb == null) {
inDb = r.createObject(DbNews.class, news.getId());
}
inDb.setPhotos(FileListMerger.mergeWithRemote(r, inDb.getPhotos(), news.getPhotos()));
r.copyToRealmOrUpdate(inDb);
});
realm.close();
}
此处mergeWithRemote
函数如下所示
public static RealmList<DbFile> mergeWithRemote(Realm realm, @NonNull RealmList<DbFile> local, @NonNull List<File> remote) {
Set<String> remoteIds = new HashSet<>();
for (File file : remote) {
remoteIds.add(file.getId());
}
Set<String> localIds = new HashSet<>();
for (DbFile file : local) {
localIds.add(file.getFileId());
}
for (int i = 0; i < local.size(); i++) {
if (!remoteIds.contains(local.get(i).getFileId())) {
local.remove(i);
i--;
}
}
for (int i = 0; i < remote.size(); i++) {
if (!localIds.contains(remote.get(i).getId())) {
DbFile newPhoto = realm.where(DbFile.class).equalTo("fileId", remote.get(i).getId()).findFirst();
if (newPhoto == null) {
newPhoto = realm.createObject(DbFile.class, remote.get(i).getId());
}
local.add(newPhoto);
}
}
return local;
}
从我的观点来看,这应该可行。但是,当我从领域获取id的新闻时,我收到了没有照片的新闻(news.getPhotos().size() == 0
)。
Realm realm = Realm.getDefaultInstance();
DbNews news = realm.where(DbNews.class)
.equalTo("newsId", newsId).findFirst()
// somewhere later
realm.close();
注意:当我在RealmBrowser中打开数据库时,我看到文件保存在文件表中,新闻保存在新闻表中,但新闻包含空文件列表。