Reusable generic base class DAOs with Android Room

前端 未结 6 2295
夕颜
夕颜 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:13

    I have a solution for findAll.

    Codes in that BaseDao:

    ...
    public List findAll() {
        SimpleSQLiteQuery query = new SimpleSQLiteQuery(
            "select * from " + getTableName()
        );
        return doFindAll(query);
    }
    ...
    public String getTableName() {
        // Below is based on your inheritance chain
        Class clazz = (Class)
            ((ParameterizedType) getClass().getSuperclass().getGenericSuperclass())
                .getActualTypeArguments()[0];
        // tableName = StringUtil.toSnakeCase(clazz.getSimpleName());
        String tableName = clazz.getSimpleName();
        return tableName;
    }
    ...
    @RawQuery
    protected abstract List doFindAll(SupportSQLiteQuery query);
    

    and other Dao looks like :

    @Dao
    public abstract class UserDao extends AppDao {
    }
    

    That's all

    The idea is

    1. Get the table name of subclass's generic type on runtime
    2. Pass that table name to a RawQuery

    If you prefer interface to abstract class, you can try optional method of java 8.

    It's not beautiful but worked, as you can see.

    I created a gist at here

提交回复
热议问题