我开始尝试Realm for Android,所以我创建了两个类:
class ProductSelection extends RealmObject {
private String selectedProductName;
private String selectedProductID;
…
}
class ProductProfile extends RealmObject {
private String profileTitle;
private RealmList< ProductSelection > productSelection;
…
}
然后我创建了几个ProductSelection对象和ProductProfile对象。
realm.beginTransaction();
ProductSelection prodSelection = realm.createObject(ProductSelection.class);
prodSelection.setSelectedProductName(prodTv.getText().toString());
prodSelection.setSelectedProductID(prodIdTv.getText().toString());
…
realm.commitTransaction();
…
realm.beginTransaction();
ProductProfile profile = realm.createObject(ProductProfile.class);
profile.setProfileTitle(“Some Title”);
RealmResults< ProductSelection > results =
realm.allObjects(ProductSelection.class);
RealmList< ProductSelection > selectionList = new RealmList<>();
for (ProductSelection selection : results) {
selectionList.add(selection);
}
profile.setProductSelection(selectionList);
realm.commitTransaction();
现在我有以下问题:
当我打电话
realm.allObjects(ProductSelection.class).clear();
似乎不仅清除了我的ProductSelection对象,还清除了属于ProductProfile类的ProductSelection对象列表,因为它们现在不再包含任何对象。是否可以防止这种情况,即删除所有ProductSelection对象,但仍保留属于ProductProfile列表的对象?
答案 0 :(得分:0)
不,没有。 Realm是一个类型化的数据库,因此您可以将RealmObject类视为SQLite表。清除它将删除所有数据,即使它是从其他类引用的。
解决方案是查询ProductSelection
个对象并明确删除它们:
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.where(ProductSelection.class).equalTo("someField", "someValue")
.findAll()
.deleteAllFromRealm();
// deleteAllFromRealm() since 0.89.0, in previous versions it's `clear()`
}
});
答案 1 :(得分:0)
我实际上无法想到支持此显式用例的简单方式,除非您使用双向映射(如果您的ProductProfile
类包含{{ 1}},然后ProductSelection
也包含其ProductSelection
)。
因为那样你就可以做到这一点
ProductProfile
但您必须自己管理此映射。