哪种方式更好?
内部循环的一个事务
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();
}
还是另一种方式?如果你知道怎么做得更好,请说。
答案 0 :(得分:1)
<tr ng-repeat="question in questionnaireData track by $index"> <td><span class="showDot">{{question.QuestionItem}}</span></td> <td> <div class="" > <select ng-if="question.MasterDataCategoryId != null" id="{{question.QuestionId}}" ng-model="question[$index]" class="form-control" ng-click="getAnswersDetails(question)"> <option selected="selected"></option> <option ng-repeat="answer in answerData" value="{{answer.MasterData}}"> {{answer.MasterData}} </option> </select> <input ng-if="question.MasterDataCategoryId == null" id="{{question.QuestionId}}" ng-model="MasterDataCategoryId[$index].QuestionId" type="text" name="question.QuestionId" class="form-control"> </div>
这个更糟糕。
首选单笔交易。
答案 1 :(得分:0)
由于您正在处理Realm Proxy对象,因此您可以遵循此方法。
public void saveProducts(List<Product> products) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
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);
realm.insertOrUpdate(product); // using insert API
}
realm.commitTransaction();
realm.close();
}