[英]Optional query parameters for Android Room
我有以下帶有查詢的 DAO:
@Dao
public interface BaseballCardDao {
@Query(
"SELECT * FROM baseball_cards " +
"WHERE brand LIKE :brand " +
" AND year = :year " +
" AND number LIKE :number " +
" AND player_name LIKE :playerName " +
" AND team LIKE :team"
)
LiveData<List<BaseballCard>> getBaseballCards(
String brand, int year, String number, String playerName, String team
);
}
String
參數是“可選的”,因為我可以通過"%%"
來匹配由於LIKE
運算符的所有行。 但是我不能用year
來做到這一點,因為它是一個int
。 一種解決方案是添加兩種不同的@Query
方法,一種帶有int year
參數,另一種沒有。 有沒有更優雅的方法來使用 Room 的@Query
創建可選參數?
這是一個遲到的答案,但正如我最近面臨的那樣,我想與那些正在尋找它的人分享我的簡單(但很愚蠢!)技巧。
正如@CommonsWare 所說,我們可以添加一個OR
語句來檢查空值,然后簡單地使我們的可選參數可以為空並為它們傳遞null
。 例如,您的查詢如下所示:
@Dao
public interface BaseballCardDao {
@Query(
"SELECT * FROM baseball_cards " +
"WHERE (:brand IS NULL OR brand LIKE :brand)" +
" AND (:year IS NULL OR year = :year)" +
" AND (:number IS NULL OR number LIKE :number)" +
" AND (:playerName IS NULL OR player_name LIKE :playerName)" +
" AND (:team IS NULL OR team LIKE :team)"
)
LiveData<List<BaseballCard>> getBaseballCards(
@Nullable String brand, @Nullable Integer year, @Nullable String number, @Nullable String playerName, @Nullable String team
);
}
或者使用 kotlin 和可選參數進行更多聲明:
@Query(
"""SELECT * FROM baseball_cards
WHERE (:brand IS NULL OR brand LIKE :brand)
AND (:year IS NULL OR year = :year)
AND (:number IS NULL OR number LIKE :number)
AND (:playerName IS NULL OR player_name LIKE :playerName)
AND (:team IS NULL OR team LIKE :team)"""
)
fun getBaseballCards(
brand: String? = null,
year: Int? = null,
number: String? = null,
playerName: String? = null,
team: String? = null
): LiveData<List<BaseballCard>>
編輯:請考慮此解決方案對於不可為空的字段很有用。 如果該字段可以為空並且您想要查找沒有該字段值的記錄,這不是正確的查詢方式,您可以考慮動態查詢創建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.