如何创建一个抽象类,该类将使用GreenDAO为任何实体模型处理基本的CRUD



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

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();
    }
}

相关内容

  • 没有找到相关文章

最新更新