Reusable generic base class DAOs with Android Room

pqvst picture pqvst · Jun 25, 2017 · Viewed 9.6k times · Source

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

public interface BaseDao<T> {

  @Insert
  void insert(T object);

  @Update
  void update(T object);

  @Query("SELECT * FROM #{T} WHERE id = :id")
  void findAll(int id);

  @Delete
  void delete(T object);

}

public interface FooDao extends BaseDao<FooObject> { ... }

public interface BarDao extends BaseDao<BarEntity> { ... }

I haven't been able to figure out any way of achieving this without having to declare the same interface members and write the query for each sub class. When dealing with a large number of similar DAOs this becomes very tedious...

Answer

Natan picture Natan · Aug 9, 2017

Today, August 08, 2017, with version 1.0.0-alpha8 the Dao below works. I can have other Dao heroing the GenericDao.

@Dao
public interface GenericDao<T> {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(T... entity);

    @Update
    void update(T entity);

    @Delete
    void delete(T entity);
}

However, GenericDao can not be included in my Database class