Optional query parameters for Android Room

后端 未结 1 1988
生来不讨喜
生来不讨喜 2021-01-05 02:07

I have the following DAO with a query:

@Dao
public interface BaseballCardDao {
    @Query(
        \"SELECT * FROM baseball_cards \" +
        \"WHERE brand          


        
相关标签:
1条回答
  • 2021-01-05 02:51

    It is a late answer but as I have faced it recently, I wanted to share my simple (but silly!) trick for those who are looking for it.

    As @CommonsWare has said, we can add an OR statement that checks for null to it and then simply make our optional parameters nullable and pass null for them. For example, your query would look like:

    @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
        );
    }
    

    Or more declarative using kotlin and optional parameters:

    @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>>
    
    0 讨论(0)
提交回复
热议问题