Android Room Fetch data with dynamic table name

倖福魔咒の 提交于 2021-01-27 14:46:20

问题


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

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