不从领域删除嵌入式对象

时间:2018-11-27 12:43:07

标签: android realm

Android Studio 3.2。 领域5.8.0

    public class Merchant extends RealmObject {
        @PrimaryKey
        private long id;
        private Image preview;
    }

    public class Image extends RealmObject {
        @PrimaryKey
        private long id;
    }

我需要删除具有特定ID的Merchants对象及其所有嵌入的对象(在我的示例中为图片)。

所以这里的代码:

         public static void updateMerchantList(final List<Merchant> thatMerchantsList) {

                Realm realm = Realm.getDefaultInstance();
                try {
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            RealmList<Merchant> localMerchantList = getMerchantsRealmList();
                            if (!EqualsUtil.areEqualContentLists(localMerchantList, thatMerchantsList)) {
                                List<Merchant> itemNotExistInThatMerchants = new ArrayList<>(localMerchantList);
                                itemNotExistInThatMerchants.removeAll(thatMerchantsList);
                                if (itemNotExistInThatMerchants.size() > 0) {
                                    localMerchantList.removeAll(itemNotExistInThatMerchants);
                                    Long[] idsToDeleteArray = new Long[itemNotExistInThatMerchants.size()];
                                    for (int index = 0; index < itemNotExistInThatMerchants.size(); index++) {
                                        Merchant merchant = itemNotExistInThatMerchants.get(index);
                                        idsToDeleteArray[index] = merchant.getId();
                                    }
                                    RealmResults<Merchant> localMerchantsForDelete = realm.where(Merchant.class).in(Merchant.ID, idsToDeleteArray).findAll();
                                    boolean isDelete = localMerchantsForDelete.deleteAllFromRealm();
                                }
                            } 
                        }
                    });
                } finally {
                    realm.close();
                }
            }

 public static RealmList<Merchant> getMerchantsRealmList() {
        Realm realm = Realm.getDefaultInstance();
        try {
            RealmResults<Merchant> realmResults = realm.where(Merchant.class).findAll();
            RealmList<Merchant> realmList = new RealmList<>();
            realmList.addAll(realmResults.subList(0, realmResults.size()));
            return realmList;
        } finally {
            realm.close();
        }
    }

结果2商家成功从Realm删除(通过方法deleteAllFromRealm)。 很好。

但是所有嵌入的对象(例如Image不能从Realm中删除。

问题:

    1. 这是因为我需要编写自定义方法,以级联删除Merchant及其所有嵌入的对象?
    1. Realm可以级联删除对象吗?

0 个答案:

没有答案