您可以僅計算項目與指定id
,而你的id
是獨一無二的,它會如果項目存在返回1和0,如果沒有,那麼你可以很容易地使一個條件:
boolean itemExists
= (YourModel.find.where().eq("id", id).findRowCount() == 1) ? true : false;
Logger.info("Item " + ((itemExists) ? "exists" : "not found!"));
在,如果你的內涵爲以JSON的例子返回現有實體另一方面,則不需要進行單獨檢查,只檢查,如果它不是空...
YourModel entity = YourModel.find.byId(id);
if (entity == null) return notFound("No such record");
// .. rest of code for preparing API...
編輯
關於費用:find.byId(id)
試圖獲取整個實體,而find.ref(id)
得到僅供參考。不幸的是,您不能確定對象是否存在ref(id)
,因爲它總是不爲空,因此,按照id計算元素的IMHO比選擇偶數單個字段檢查Db是否返回實體要便宜。
其實find.byId(id)
是最昂貴的選擇,因爲它加載整個實體,以及優化的API通常最好使用Ebean的select()
和fetch()
,喜歡寫專門的方法:
YourModel e = YourModel.find.select("id, name, age").where().eq("id", id).findUnique();
或
List<YourModel> le = YourModel.find.select("id, name, age").where().eq("id", id).findList();
我想要看看是否有一種方法可以使用延遲加載來實現,通過獲取引用而不是整個對象。也許我正在試圖做不必要的優化。我甚至不知道調用的成本是多少(find.ref(id)vs find.byId(id))。 – user724535
我想第一個選項會起作用。我正在使用它來刪除,所以我不需要json。只是想知道該項目是否存在並且已被刪除。 – user724535