[英]Error Performing an update in Realm
我正在嘗試更新RelamObject(在這種情況下為RealmCase)內部的屬性。 我嘗試了下面的代碼,盡管我在RealmPatientInfo表中確實看到了一個新對象,但似乎沒有任何更新,但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.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();
任何意見是極大的贊賞。
您還應該RealmPatientInfo
類保存到該領域,以使其得到管理。
try {
RealmPatientInfo patientInfo = new RealmPatientInfo(patientInfo);
patientInfo = realm.copyToRealmOrUpdate(patientInfo);
persistedCase.setPatientInfo(patientInfo);
realm.copyToRealmOrUpdate(realmCase);
realm.commitTransaction();
} catch(Exception e) {
if(realm != null) {
try {
realm.cancelTransaction();
} catch(Exception e) {
Log.e(TAG, "Failed to cancel transaction", e);
}
}
} finally {
if(realm != null) {
realm.close();
}
}
如果您想更換PatientInfo
對象在RealmCase
同時確保舊的對象是正確刪除,你可以做到以下幾點:
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
之類的設置屬性要求對象首先要持久化。 這可能是我們應該重新考慮的事情,以便行為更加一致。 這也意味着您的第一個代碼示例將正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.