Passing in a string to use as part of a Room query

房东的猫 提交于 2020-04-17 22:50:26

问题


Why does this not work in Room?:

val dataSourceFactory =
    database.gameDao.getGames("Game.platforms LIKE '%XONE%'")

@Query("SELECT * FROM Game WHERE :likeClause")
fun getGames(likeClause: String): DataSource.Factory<Int, Game>

But this does?:

@Query("SELECT * FROM Game WHERE Game.platforms LIKE '%XONE%'")
fun getGames(): DataSource.Factory<Int, Game>

Is there any way to pass in a string that can stand in as part of the query?

EDIT: I know this isn't the correct way to form a single LIKE clause, but I'm actually trying to pass in multiple LIKE clauses. So I want a way to inject text directly into the query, but Room doesn't seem to want me to do that.


回答1:


You are talking about dynamic SQL and I dont think this is possible with room. what would work is

@Query("SELECT * FROM Game WHERE Game.platforms LIKE :likeClause1 AND Game.publisher LIKE :likeClause2")
fun getGames(likeClause1: String, likeClause2: String): DataSource.Factory<Int, Game>

and you can use either AND or OR as needed and if you want to ignore one of the like clauses just pass an empty string



来源:https://stackoverflow.com/questions/60559971/passing-in-a-string-to-use-as-part-of-a-room-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!