使用SQLite处理POJO的DAO创建的更好模式

时间:2016-04-08 18:39:36

标签: java android sqlite design-patterns ormlite

我正在使用 SQLCipher 适用于Android的ORMLite 的Android应用程序来处理使用SQLite和杰克逊的POJO存储用于解析。

我想知道是否会有一个更好的模式,我使用的(stayforit推荐)获得与给定的实体类相对应的DAO。我有超过30个实体类,我不断添加一些时间,每次,我必须创建一个看起来与前一个完全相同的DAO类。我怎么能使用泛型类进行推广?

这是我的DbManager类:

public class DbManager {
    private static DbManager instance;
    private CipherDbHelper dbHelper;
    private SecureSharedPreferences settings;

    private DbManager() {

    }

    private DbManager(Context context, String password) {
        SQLiteDatabase.loadLibs(context);
        dbHelper = new CipherDbHelper(context, password);
    }

    public static void init(Context context, String password) {
        instance = new DbManager(context, password);
    }

    public static DbManager getInstance() {
        if (instance == null) {
            Log.e("DbManager", "DbManager is null");
        }
        return instance;
    }

    public <D extends Dao<T, String>, T> D getDAO(Class<T> clz) throws SQLException {
        return dbHelper.getDao(clz);
    }
}

以下是每次向项目添加POJO实体时需要生成的循环DAO类的示例:

public class CategoriesDAO extends BaseDAO<EntityCategories> {
    private static CategoriesDAO instance;

    private CategoriesDAO() {
    }

    public synchronized static CategoriesDAO getInstance() {
        if (instance == null) {
            instance = new CategoriesDAO();
        }
        return instance;
    }

    @Override
    public Dao<EntityCategories, String> getDAO() throws SQLException, java.sql.SQLException {
        return DbManager.getInstance().getDAO(EntityCategories.class);
    }
}

以下是我在Activity中使用它的方法:

CategoriesDAO.getInstance().addOrUpdate(categories);

2 个答案:

答案 0 :(得分:3)

这就是我喜欢使用Ormlite DAO的方式:

CRUDOperator:

public interface CRUDOperator<T> {

    void create(T obj);

    void update(T obj);

    void delete(T obj);
}

回购:

public interface Repo<T> extends CRUDOperator<T>{

    Optional<T> queryForId(Integer id);
    ObservableList<T> queryForAll();
    ...
}

OrmliteRepo:

public class OrmliteRepo<T> implements Repo<T> {

    protected Dao<T, Integer>          dao;

    protected OrmliteRepo(Dao<T, Integer> dao) {
        this.dao = dao;
    }

    public ObservableList<T> queryForAll() throws SQLException {
        List<T> results =  dao.queryForAll();
        return Validators.isNullOrEmpty(results) ? FXCollections.observableArrayList() : FXCollections.observableArrayList(results);
    }

    public Optional<T> queryForId(Integer id) throws SQLException {
        T result = dao.queryForId(id);
        return Optional.ofNullable(result);
    }

    @Override
    public void create(T obj) throws SQLException {
            dao.create(obj);
    }

    @Override
    public void update(T obj) throws SQLException {
            dao.update(obj);
    }

    @Override
    public void delete(T obj) throws SQLException {
            dao.delete(obj);
    }
}

YourRepo:

public class YourRepo extends OrmliteRepo<YourModel> {

    public YourRepo(Dao<YourModel, Integer> dao) {
        super(dao);
    }
}

RepoService:

public interface RepoService {
    <T> Repo<T> get(Class<T> dataClass);
}

BaseRepoService:

public class BaseRepoService implements RepoService {

    private RepoFactory            repoFactory;
    private Map<Class<?>, Repo<?>> repoCache;

    public BaseRepoService(RepoFactory repoFactory) {
        this.repoFactory = repoFactory;
        repoCache = new HashMap<>();
    }

    @Override
    public <T> Repo<T> get(Class<T> dataClass) {
        @SuppressWarnings("unchecked")
        Repo<T> repo =  (Repo<T>) repoCache.get(dataClass);

        if (repo == null) {
            repo = createRepo(dataClass);
            repoCache.put(dataClass, repo);
        }
        return repo;
    }

    private <T> Repo<T> createRepo(Class<T> dataClass) {
        return repoFactory.createRepo(dataClass);
    }
}

RepoFactory:

public interface RepoFactory {
    public <T> Repo<T> createRepo(Class<T> dataClass);
}

OrmliteRepoFactory:

public class OrmliteRepoFactory implements RepoFactory {

    private DbAccess                                      dbAccess;
    private final Map<Class<?>, Supplier<OrmliteRepo<?>>> suppliers;

    public OrmliteRepoFactory(DbAccess dbAccess) {
        this.dbAccess = dbAccess;

        suppliers = new HashMap<>();
        suppliers.put(YourModel.class, () -> new YourRepo(getDao(YourModel.class)));
    }

    private <T> Dao<T, Integer> getDao(Class<T> modelClass) {
        return dbAccess.getDaoImplementation(modelClass);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> OrmliteRepo<T> createRepo(Class<T> dataClass) {
        return (OrmliteRepo<T>) suppliers.get(dataClass).get();
    }
}

DBACCESS:

public interface DbAccess {
     <T, R> R getDaoImplemantation(Class<T> dataClass);
}

OrmliteDbAccess:

public class OrmliteDbAccess implements DbAccess{

@Override
public <T, R> R getDaoImplementation(Class<T> objectClass) {
    R dao = null;

    try {
        dao = DaoManager.createDao(connectionSource, objectClass);

    } catch (SQLException e) {
        LOGGER.error("Error getting dao for class {}; {}", objectClass, e);
    }
    return dao;
}

}

现在您需要做的就是将repos的供应商添加到repoFactory,并使YourRepo.class扩展OrmliteRepo.class。如果我需要一些特定仓库的额外行为,我会把它放在repo实现中。

当您有RepoService的实例时:

RepoService repoService = new BaseRepoService(ormliteRepoFactory);

你可以这样访问你的回购:

Repo<YourModel> repo = repoService.get(YourModel.class);

答案 1 :(得分:2)

您可以将您的POJO daos的实例存储在BaseDao本身或子类中的地图中,然后使用未经检查的强制转换将其解压缩。

public class GenericDao<T> extends BaseDao<T>  {

  private static class InstanceHolder {
      static final Map<Class<?>, GenericDao<?>> INSTANCES = new HashMap<>();
  }

  public static synchronized <T> GenericDao<T> getInstance(Class<T> clazz) {
      GenericDao<T> dao = (GenericDao<T>)InstanceHolder.INSTANCES.get(clazz);
      if (dao == null) {
        dao = new GenericDao<T>();
        InstanceHolder.INSTANCES.put(clazz, dao);
      }
      return dao;
  }

  private GenericDao() {
  }
}

然后

    GenericDao<EntityCategories> foo = GenericDao.getInstance(EntityCategories.class);
    foo.addOrUpdate(....);