有没有办法为 Room Persistence Library 创建 Generic DAO class
Is there a way to create Generic DAO class for Room Persistence Library
我正在使用 Room Persistence Library 并且我试图通过创建一个通用 DAO class 来避免样板代码,就像这样
@Dao
public interface PendingTaskDao<V> {
@Query("SELECT * FROM :tableName")
Maybe<List<V>> getAllEntitiesFrom(String tableName);
}
但是编译器抱怨 <table or subquery> expected got : tableName
。有没有办法创建通用 DAO,或者库必须以这种方式工作以防止 SQL injection?
为了防止 SQL 注入 ,库必须以这种方式工作,是的,你是对的。
来自@Query
的docs:
This query is verified at compile time by Room to ensure that it compiles fine against the database.
所以为了让查询正确编译,你必须提供一个表名,不是作为参数,而是直接在查询中,硬编码
虽然,您不能为所有实体的所有操作创建一个通用的 DAO,但您至少可以创建一个 BaseDao 来通用化 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
会去实体的具体道。
我正在使用 Room Persistence Library 并且我试图通过创建一个通用 DAO class 来避免样板代码,就像这样
@Dao
public interface PendingTaskDao<V> {
@Query("SELECT * FROM :tableName")
Maybe<List<V>> getAllEntitiesFrom(String tableName);
}
但是编译器抱怨 <table or subquery> expected got : tableName
。有没有办法创建通用 DAO,或者库必须以这种方式工作以防止 SQL injection?
为了防止 SQL 注入 ,库必须以这种方式工作,是的,你是对的。
来自@Query
的docs:
This query is verified at compile time by Room to ensure that it compiles fine against the database.
所以为了让查询正确编译,你必须提供一个表名,不是作为参数,而是直接在查询中,硬编码
虽然,您不能为所有实体的所有操作创建一个通用的 DAO,但您至少可以创建一个 BaseDao 来通用化 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
会去实体的具体道。