Reusable generic base class DAOs with Android Room

前端 未结 6 2279
夕颜
夕颜 2020-12-23 18:30

Is there any way to create reusable generic base class DAOs with Android Room?

public interface BaseDao {

  @Insert
  void insert(T object);

  @Up         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 19:05

    Although I agree with your thinking, the answer is no. For several reasons.

    1. When the fooDao_Impl.java is generated from your @Dao fooDao extends BaseDao class, you will be met with a lot of "cannot find class Symbol T" errors. This is due to the method Room uses to generate dao implementations. This is a method that will not support your desired outcome, and is unlikely to change soon (in my opinion, due to type erasure).

    2. Even if this is resolved, Room does not support dynamic @Dao queries, in an effort to prevent SQL injection. This means you can only dynamically insert values into queries, not column names, table names, or query commands. In the example you have you could not use #{T} as it would breach this principle. In theory if the problem detailed in point 1 is resolved you could user insert, delete and update though.

提交回复
热议问题