我需要創建一個具有2個條件的方法,首先如果對象存在於領域,如果存在,則返回它,如果不存在,則創建它並返回它。如何在java中創建後返回領域對象
public RouteModel findOrInitById(final Long webId) {
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
RouteModel routeModel = realm.copyFromRealm(
realm.where(RouteModel.class).equalTo("routeWebId", webId).findFirst());
if (routeModel != null) {
return routeModel;
} else {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Number currentIdNum = realm.where(RouteModel.class).max("routeId");
int nextId;
if (currentIdNum == null) {
nextId = 1;
} else {
nextId = currentIdNum.intValue() + 1;
}
RouteModel newRouteModel = new RouteModel.Builder()
.setRouteId(nextId)
.setWebId(webId)
.build();
realm.copyToRealmOrUpdate(newRouteModel);
}
});
//here i need to return the "new " object
}
} finally {
if (realm != null) {
realm.close();
}
}
return null;
}
還有什麼方法可以返回沒有查詢的對象嗎?
,你可以在我的代碼中看到的,我只是一個事務裏的新境界對象,我想無需查詢即可返回新對象的副本 – Spaceghost87