How to use parameter fields in Room @Query?

╄→尐↘猪︶ㄣ 提交于 2020-05-28 13:33:07

问题


I have a User class with a field id, so I wanted to run the following query with Room:

@Query("SELECT * FROM ticket where user_id = :user.id")
LiveData<Ticket> loadFromUser(User user);

But I am getting error marks on Android Studio on user.id and all examples I find online only use the direct parameter of the @Query method, usually a String or an int.

Is it possible to use an object's field in a Room @Query? If positive, so what's the proper way of referencing it.


回答1:


You can't pass parameters like that to room. It does not support a full expression language. You have to use primitive types to pass parameters. Like this,

@Query("SELECT * FROM ticket where user_id = :user_id")
LiveData<Ticket> loadFromUser(String user_id);



回答2:


in my case i used @RawQuery

in DAO you can write

@RawQuery
LiveData<Ticket> loadFromUser(SupportSQLiteQuery query);

and create your query and pass to it.

SimpleSQLiteQuery query  = new SimpleSQLiteQuery("SELECT * FROM ticket where user_id = ?") , new Object[]{user.id})

and pass this query to DAO method.

userDao.loadFromUser(query)


来源:https://stackoverflow.com/questions/51851243/how-to-use-parameter-fields-in-room-query

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