Android Room的可选查询参数

问题描述 投票:4回答:1

我有以下带有查询的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有没有更优雅的方法来创建可选参数?

android dao android-room optional-parameters
1个回答
0
投票
这是一个很晚的答案,但是正如我最近遇到的那样,我想与那些正在寻找它的人分享我的简单(但很愚蠢!)技巧。

正如@CommonsWare所说的,我们可以添加一个OR语句来检查是否为null,然后简单地使我们的可选参数为空,并为它们传递null。例如,您的查询如下所示:

@Dao public interface BaseballCardDao { @Query( "SELECT * FROM baseball_cards " + "WHERE 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>>

© www.soinside.com 2019 - 2024. All rights reserved.