39

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.

Michel Feinstein
  • 13,416
  • 16
  • 91
  • 173
  • 2
    This would be a much needed feature, especially in the case you need to use a high number of members of a class. – AndrewBloom Feb 10 '20 at 11:24

3 Answers3

50

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);
NirmalCode
  • 2,140
  • 1
  • 14
  • 19
8

A simple solution is to create two other functions, one is for user_id and one is for user as follows:

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

@Transaction
LiveData<Ticket> loadFromUser(User user){
   return loadFromUser(user.id);
}
T D Nguyen
  • 7,054
  • 4
  • 51
  • 71
5

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)
Mojtaba Haddadi
  • 1,346
  • 16
  • 26