Android Room 的可选查询参数

Cod*_*ice 10 android dao optional-parameters 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
    );
}
Run Code Online (Sandbox Code Playgroud)

String参数是在意义上的“可选”我可以通过"%%"匹配所有行,由于LIKE运营商。但我不能这样做,year因为它是一个int. 一种解决方案是添加两种不同的@Query方法,一种带int year参数,另一种不带。有没有更优雅的方法来创建带有 Room 的可选参数@Query

mom*_*t99 7

这是一个迟到的答案,但正如我最近面临的那样,我想与那些正在寻找它的人分享我的简单(但很愚蠢!)技巧。

正如@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
    );
}
Run Code Online (Sandbox Code Playgroud)

或者使用 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>>
Run Code Online (Sandbox Code Playgroud)

编辑:请考虑此解决方案对于不可为空的字段很有用。如果该字段可以为空并且您想要查找没有该字段值的记录,这不是正确的查询方式,您可以考虑动态查询创建。