Le Hoang Long
Le Hoang Long

Reputation: 500

How to use object property in Android Room SQL?

In Room, we can make a query from DAO with fundamental data type like follow

@Query("SELECT * FROM Table WHERE name=:name)
fun fetchAll(name: String)

Is it possible to pass and object and use its property instead like following

@Query("SELECT * FROM Table WHERE name=:object.name)
fun fetchAll(object: ClassA)

I could not find anywhere saying how to do it, so i'm not sure if it is possible and how to do it. When I try it in Android Studio, it is indicating error

Upvotes: 9

Views: 1153

Answers (2)

Mukund Jogi
Mukund Jogi

Reputation: 1395

In RoomDatabase query you can try the query with multiple variations i.e.

@Query("SELECT * FROM users WHERE label LIKE :query")
  fun pagingSource(query: String): PagingSource<Int, User>

@Query("SELECT * from user WHERE region IN (:regions)")
    fun loadUsersByRegion(regions: List<String>): Flow<List<User>>

@Query("Select * from table_vehicles where key_id = :vehicleId")
 fun getVehicleDetails(vehicleId: String) : LiveData<List<VehicleModel?>>

But when you use where keyword you need to pass specific value or custom query for your results. Passing custom object may result into error. As after the ":" indicates value-parameter and you cannot add model.id.

Hope it will help you.

Upvotes: 3

Aymen Ben Salah
Aymen Ben Salah

Reputation: 499

Until now i think there is no way to pass an object as paramter but you can use @RawQuery

in DAO you can write

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

and create your query and pass to it.

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

and pass this query to DAO method.

yourDao.loadFromUser(query)

Upvotes: 0

Related Questions