gpt4 book ai didi

android - Android Room 的可选查询参数

转载 作者:行者123 更新时间:2023-12-03 13:26:43 29 4
gpt4 key购买 nike

我有以下带有查询的 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 匹配所有行运算符(operator)。但我不能用 year 做到这一点因为它是 int .一种解决方案是添加两个不同的 @Query方法,一种是 int year参数和其他没有。有没有更优雅的方法来使用 Room 的 @Query 创建可选参数? ?

最佳答案

这是一个迟到的答案,但正如我最近遇到的那样,我想为那些正在寻找它的人分享我的简单(但愚蠢!)技巧。
正如@CommonsWare 所说,我们可以添加 OR检查 null 的语句,然后简单地使我们的可选参数为 null 并传递 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>>
编辑:
请考虑此解决方案对于不可为空的字段很有用。如果该字段可以为空,并且您想查找该字段没有值的记录,则这不是正确的查询方式,您可以考虑创建动态查询。

关于android - Android Room 的可选查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029435/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com