Android Room的选项查询参数

时间:2018-08-26 19:07:28

标签: android dao android-room optional-parameters

我对以下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来匹配所有行。但是由于yearint,因此我无法使用它。一种解决方案是添加两种不同的@Query方法,一种带有int year参数,另一种不带有。是否可以使用Room的@Query创建可选参数的更优雅的方式?

1 个答案:

答案 0 :(得分:5)

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

就像@CommonsWare所说的,我们可以添加一个OR语句来检查是否为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>>