[英]Is there a way to create Generic DAO class for Room Persistence Library
我正在使用Room Persistence Library,並且嘗試通過創建Generic DAO類來避免樣板代碼,例如
@Dao
public interface PendingTaskDao<V> {
@Query("SELECT * FROM :tableName")
Maybe<List<V>> getAllEntitiesFrom(String tableName);
}
但是編譯器抱怨<table or subquery> expected got : tableName
。 有沒有一種創建通用DAO的方法,或者該庫必須以這種方式工作才能防止SQL注入 ?
該庫必須以這種方式工作才能防止SQL注入 ,是的,您是對的。
從@Query
的文檔中:
Room會在編譯時驗證此查詢,以確保可以對數據庫進行正確的編譯。
因此,要讓查詢正確編譯,您必須提供一個tableName而不是作為參數,而是直接在查詢中進行硬編碼
雖然不能為所有實體的所有操作創建通用DAO,但至少可以創建BaseDao來insertAll
insert
, insertAll
, update
, updateAll
, delete
和deleteAll
操作。
/**
* Created by Yousuf Sohail on 10/7/18.
*/
interface BaseDao<T> {
/**
* Insert an object or array of objects in the database.
*
* @param obj the objects to be inserted.
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(vararg obj: T): LongArray
/**
* Update an object or array of objects from the database.
*
* @param obj the object to be updated
*/
@Update
fun update(vararg obj: T)
/**
* Delete an object or array of objects from the database
*
* @param obj the object to be deleted
*/
@Delete
fun delete(vararg obj: T)
}
select
和selectAll
將轉到特定的實體Daos。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.