2016-05-25 87 views
0

我想創建一個抽象類來調用Dao來插入任何實體對象,以避免在每個類中編寫重複的代碼實現IRepository如何使用GreenDAO創建抽象類來處理任何實體模型

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 
} 

我不明白,我應該用什麼樣的語法來指定變量entity是什麼insert()期待。

+1

AbstractDao的 - 那兩個通用PARAMS?從邏輯上講,它們是E - 實體類型和主鍵類型 - 因此,如果您使用Integer作爲PK,那麼聲明AbstractDao aviad

+1

DaoSession已經涵蓋了其中的一些內容。這不僅僅是訪問DAO,還提供了CRUD方法。 –

回答

0

好我得到了它的specifiying 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(); 
    } 
} 
相關問題