如何创建一个抽象 class 来处理任何实体模型的 GreenDAO 基本 CRUD

How to create an abstract class that will handle basic CRUD with GreenDAO for any Entity model

我想创建一个抽象 class,它将调用 Dao 来插入任何实体对象,以避免在每个实现 IRepository 的 class 中编写重复代码,

public abstract class DBStore<T> implements IRepository {
    DaoMaster daoMaster;
    Class<T> entityClass; 

    public DBStore(DaoMaster daoMaster, Class<T> entityClass) {
        this.daoMaster = daoMaster;
        this.entityClass = entityClass;
    }

    @Override
    public void add(Entity entity) {
        DaoSession session = this.daoMaster.newSession();
        AbstractDao<?, ?> dao = session.getDao(this.entityClass);
        dao.insert(entity);  // cannot pass entity as parameter because insert() expects capture<?>
    }

    // Other CRUD methods
}

我不明白应该使用什么语法来指定变量 entityinsert() 所期望的。

好的,我通过指定 DBStore<T extends Entity> implements IRepository<T> 让它工作了 并将 AbstractDao<?, ?> 转换为 AbstractDao<T, Long>

完整代码如下:

public abstract class DBStore<T extends Entity> implements IRepository<T> {
    DaoMaster daoMaster;
    Class<T> entityClass;

    public DBStore(DaoMaster daoMaster, Class<T> entityClass) {
        this.daoMaster = daoMaster;
        this.entityClass = entityClass;
    }

    @Override
    public void add(T entity) {
        this.getSession().insert(entity);
    }

    @Override
    public T getById(long id) {
        AbstractDao<T, Long> dao = this.getDao();
        return dao.load(id);
    }

    //other methods

    protected AbstractDao<T, Long> getDao(){
        DaoSession session = this.daoMaster.newSession();
        return (AbstractDao<T, Long>) session.getDao(this.entityClass);
    }

    protected DaoSession getSession(){
        return this.daoMaster.newSession();
    }
}