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>>
Edit:
Please consider that this solution is useful for non-nullable fields. If the field is nullable and you want to look for the records which don't have a value for the field, this is not the correct way of querying and you may consider dynamic query creation.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…