我想创建一个抽象类,它将调用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
}
我不明白我应该使用什么语法来指定变量entity
是insert()
所期望的。
答案 0 :(得分:0)
好的,我通过指定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();
}
}