How to dynamically query the room database at runtime?

后端 未结 8 1867
青春惊慌失措
青春惊慌失措 2020-11-30 05:42

The problem

Is it possible construct a query at runtime?


Use case

@Query(\"SELECT * FROM playlist \" +
        \"WHERE play         


        
8条回答
  •  甜味超标
    2020-11-30 06:05

    Instead of writing multiple query i refer pass negative value to limit clause. Because if there is change in query i have to update the both query which is more error prone.

    Official doc -> If the LIMIT expression evaluates to a negative value, then there is no upper bound on the number of rows returned. you can find it here https://sqlite.org/lang_select.html and read the limit clause section.

    So I would do somthing like this,

    @Query("SELECT * FROM playlist " +
        "WHERE playlist_title LIKE '% :playlistTitle %' " +
        "GROUP BY playlist_title " +
        "ORDER BY playlist_title " +
        "LIMIT :limit")
    List searchPlaylists(String playlistTitle, int limit);
    

    and pass negative when you don't want to apply filter.

    return playlistDao.searchPlaylists(title, limit.isPresent() ? limit.get() : -1)
    

    It's working in my case.

    Updated [21 Dec 2018]

    In case If you are using kotlin use default value.

    @JvmOverloads
    @Query("SELECT * FROM playlist " +
            "WHERE playlist_title LIKE '% :playlistTitle %' " +
            "GROUP BY playlist_title " +
            "ORDER BY playlist_title " +
            "LIMIT :limit")
    fun searchPlaylists(playlistTitle: String, limit: Int = -1): List
    

    @JvmOverloads to make it compatiable with Java. It generate two separate methods for Java.

提交回复
热议问题