我有一个BeaconBase类,其中包含BeaconData列表。
public class BeaconBase extends RealmObject {
@PrimaryKey
private Integer checkInID;
@SerializedName("beacons")
@Expose
private RealmList<BeaconData> beacons;
}
public class BeaconData extends RealmObject {
@SerializedName("scanId")
@Expose
private String scanId;
@SerializedName("distance")
@Expose
private String distance;
}
BeaconData通常会很大。每小时可能大约有100000行。删除相关的BeaconBase记录时如何有效删除BeaconData?
我仅在BeaconBase中具有主键。
因此,当我删除BeaconBase记录时,成千上万个BeaconData记录被孤立了。我如何有效处理这种情况?
答案 0 :(得分:1)
try(Realm r = Realm.getDefaultInstance)) {
r.executeTransaction((realm) -> {
RealmResults<BeaconBase> beaconsToDelete = realm.where(BeaconBase.class)./*query here*/.findAll();
for(int i = beaconsToDelete.size() - 1; i >= 0; i--) {
BeaconBase beaconBase = beaconsToDelete.get(i);
beaconBase.getBeacons().deleteAllFromRealm();
beaconBase.deleteFromRealm();
}
});
}
虽然要多用一点,但您也可以这样做:
public class BeaconBase extends RealmObject {
@PrimaryKey
private Integer checkInID;
@SerializedName("beacons")
@Expose
private RealmList<BeaconData> beacons;
}
public class BeaconData extends RealmObject {
@SerializedName("scanId")
@Expose
private String scanId;
@SerializedName("distance")
@Expose
private String distance;
@LinkingObjects("beacons")
private final RealmResults<BeaconBase> beaconDataOf = null;
}
try(Realm r = Realm.getDefaultInstance)) {
r.executeTransaction((realm) -> {
realm.where(BeaconBase.class)./*query here*/.findAll().deleteAllFromRealm();
realm.where(BeaconData.class).isEmpty("beaconDataOf").findAll().deleteAllFromRealm();
});
}