gpt4 book ai didi

java - 在 Realm 中执行更新时出错

转载 作者:行者123 更新时间:2023-11-29 20:14:06 25 4
gpt4 key购买 nike

我正在尝试更新我的 RelamObject(在本例中为 RealmCase)中的一个属性。我尝试了下面的代码,虽然我确实在 RealmPatientInfo 表中看到了一个新对象,但我的 Realm 中似乎没有任何更新,只是没有从我的 RealmCase 创建关系。

    RealmCase realmCase = new RealmCase();
realmCase.setId(getId());
realmCase.setPatientInfo(new RealmPatientInfo(patientInfo));
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(realmCase);
realm.commitTransaction();
realm.close();

我也尝试了以下方法,但出现异常,提示该值不受 Realm 管理。

    Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmQuery<RealmCase> query = realm.where(RealmCase.class);
RealmCase persistedCase = query.findFirst();
persistedCase.setPatientInfo(new RealmPatientInfo(patientInfo));
realm.copyToRealmOrUpdate(realmCase);
realm.commitTransaction();
realm.close();

我还想删除旧的 patientInfo 对象(引用和 RealmPatientInfo 表中的条目)下面是我的尝试,尽管我之前的错误阻止了我测试该部分。

        Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmQuery<RealmCase> query = realm.where(RealmCase.class);
RealmCase persistedCase = query.findFirst();
if(persistedCase.getPatientInfo() != null) {
persistedCase.getPatientInfo().removeFromRealm();
persistedCase.setPatientInfo(null);
}

persistedCase.setPatientInfo(new RealmPatientInfo(patientInfo));
realm.copyToRealmOrUpdate(realmCase);
realm.commitTransaction();
realm.close();

非常感谢任何建议。

最佳答案

如果您想替换 RealmCase 中的 PatientInfo 对象,同时确保正确删除旧对象,您可以执行以下操作:

Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmQuery<RealmCase> query = realm.where(RealmCase.class);
RealmCase persistedCase = query.findFirst();
PatientInfo oldPatientInfo = persistedCase.getPatientInfo();
if(oldPatientInfo != null) {
oldPatientInfo.removeFromRealm();
}

// New Objects either have to be copied first or created using createObject
PatientInfo newPatientInfo = realm.copyToRealm(new RealmPatientInfo(patientInfo));
persistedCase.setPatientInfo(newPatientInfo);
}
});
} finally {
if(realm != null) {
realm.close();
}
}

现在您必须手动删除旧的 PatientInfo,而级联删除会自动发生:https://github.com/realm/realm-java/issues/1104

另外,例如RealmList 支持在使用 list.add(item) 时自动将对象复制到 Realm,设置属性如 setPatientInfo 需要先持久化对象。这可能是我们应该重新审视的事情,以便行为更加一致。这也意味着您的第一个代码示例可以正常工作。

关于java - 在 Realm 中执行更新时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34302272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com