I wonder how to avoid hard coding when using table name in Android Room query. I develop in Kotlin
, but to be honest in this problem it doesn't matter is Java or Kotlin.
Let's see that simple classes:
DAO interface:
@Dao
interface UserDAO {
@Query("SELECT * FROM USER")
fun getAll(): List<User>
}
Entity class:
@Entity(tableName = "USER")
class User {
}
You can see that the table name "USER" is hard coded in @Query in UserDAO. How to avoid that? How to refer to @Entity parameter tableName?
I would like to have all names in one and only one place.
You can make a constant in any of Util classes and can refer that variable in Entity and Dao class like this:-
Suppose in MainActivity you have
companion object {
const val TABLE_NAME: String="Cheese"
}
Entity class
@Entity(tableName = MainActivity.TABLE_NAME)
and Dao class will be
@Query("SELECT * FROM "+MainActivity.TABLE_NAME)
Note :- This is an usual approach to avoid hard coded naming may be you can get table name from Entity class(Needs to be explored) :) .