Welcher Weg ist besser?Realm-Schleife in einer Transaktion VS eine Transaktion für jede Stepin-Schleife
Eine Transaktion mit einer Schleife in
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(); }
Eine Schleife mit Transaktionen für jedes Element?
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(); }
Oder eine andere Art und Weise? Wenn Sie wissen, wie es besser geht, sagen Sie bitte.
Warum eine neue Transaktion pro Artikel beginnen? – EpicPandaForce
@EpicPandaForce Ich habe das für ein Szenario wie angenommen, er braucht ein einzelnes Objekt ändern Listener. Ich habe meine Antwort für single time init und commit aktualisiert, was als besserer Ansatz angesehen werden kann. – Aks4125
Es funktionierte für mich. Besser als angenommene Antwort. Danke;) +1 –