どちらが良いですか?各要素のための取引に1つのトランザクション内の領域ループVS 1つのステップループごとに1つのトランザクション
public void saveProducts(List<Product> products) {
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(realm1 -> {
for (Product product : products) {
Number currentIdNum = realm1.where(Product.class).max("id");
long nextId;
if (currentIdNum == null) {
nextId = 1;
} else {
nextId = currentIdNum.longValue() + 1;
}
String code = product.getCategory().getCode();
Category code1 = realm.where(Category.class).equalTo("code", code).findFirst();
if (code1 == null) {
Category category = realm.copyToRealmOrUpdate(product.getCategory());
product.setCategory(category);
} else {
product.setCategory(code1);
}
product.setId(nextId);
realm1.insertOrUpdate(product); // using insert API
}
});
realm.close();
}
ループ内ループを有する
つのトランザクション?
public void saveProducts(List<Product> products) { Realm realm = Realm.getDefaultInstance(); for (Product product : products) { realm.executeTransaction(realm1 -> { Number currentIdNum = realm1.where(Product.class).max("id"); long nextId; if (currentIdNum == null) { nextId = 1; } else { nextId = currentIdNum.longValue() + 1; } String code = product.getCategory().getCode(); Category code1 = realm.where(Category.class).equalTo("code", code).findFirst(); if (code1 == null) { Category category = realm.copyToRealmOrUpdate(product.getCategory()); product.setCategory(category); } else { product.setCategory(code1); } product.setId(nextId); realm1.insertOrUpdate(product); // using insert API }); } realm.close(); }
それとも別の方法はありますか?あなたがそれをより良くする方法を知っているならば、どうか言ってください。
アイテムごとに新しいトランザクションを開始するのはなぜですか? – EpicPandaForce
@EpicPandaForce彼は単一のオブジェクト変更リスナーが必要であると仮定した場合のシナリオでこれを行いました。私は、より良いアプローチと見なすことができる単一のinitとコミットのための私の答えを更新しました。 – Aks4125
それは私のために働いた。より良く受け入れられた答え。ありがとう;)+1 –