问题
Is it possible to fetch data
by passing the table name
as a parameter
? Something like this.
@Query("SELECT id, name from :tableName")
fun getData(tableName: String): List<RandomModel>
回答1:
Try this
@Dao
interface RawDao {
@RawQuery
List<RandomModel> getData(SupportSQLiteQuery query);
}
SimpleSQLiteQuery query = new SimpleSQLiteQuery("SELECT * FROM "+ tablename);
List<RandomModel> models = rawDao.getUserViaQuery(query);
回答2:
I think Room
does not support dynamic tableName
.
We have two ways:
1-In DAO
, we can replace tableName
with the actual table name, as defined on the model @Entity
2-We can use @RawQuery
like this :
@Dao
interface RawDao {
@RawQuery
User getUserViaQuery(SupportSQLiteQuery query);
}
SimpleSQLiteQuery query = new SimpleSQLiteQuery("SELECT * FROM User WHERE id = ? LIMIT 1",
new Object[]{userId});
User user2 = rawDao.getUserViaQuery(query);
You can study more at this
回答3:
you first create in your Dao a @RawQuery. just Class1, Class2, etc with the tables/classes that you are interested to monitor.
@RawQuery( observedEntities = [Class1::class, CLass2::class] )
fun query(query:SupportSqliteQuery): List<RandomModel>
To use it just create a SimpleSqliteQuery with the necessary input argument.
note there is a difference between "SupportSqlite..." used in Dao and "SimpleSqlite..." used in the doQuery() function
fun doQuery(tableName:String):List<RandomModel> {
//note $ sign in front of tableName instead of : sign
val simpleSqliteQuery = SimpleSqliteQuery("SELECT id, name from $tableName")
return dao().query( simpleSqliteQuery )
}
来源:https://stackoverflow.com/questions/59764603/android-room-fetch-data-with-dynamic-table-name