问题描述
我正在使用使用 SQLCipher , Android的 ORMLite 的Android应用程序,以处理使用SQLite和 Jackson 存储的POJO进行解析
I'm working on an Android App that use SQLCipher, ORMLite for Android to handle to POJO storing with SQLite and Jackson for parsing.
我想知道是否会有更好的模式,我正在使用(由)获取与给定的Entity类对应的DAO。我有超过30个Entity类,我不断添加一些时间,每次,我必须创建一个与前一个类似的DAO类。我如何推广使用泛型类?
I'm wondering if there would be a better pattern that the one i'm using (Recommended by stayforit) to get the DAO corresponding to the Entity class given. I have over 30 Entity class and I keep adding some over the time and each time, I have to create a DAO class that looks exactly the same as the previous one. How could I generalize using a generic class?
这是我的DbManager类:
Here is my DbManager class:
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);
}
}
这是一个我需要的经常性DAO类的例子生成每次我在项目中添加POJO实体时:
Here is an example of a recurrent DAO class I need to generate each time I add a POJO entity to my project:
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);
}
}
这是我如何在一个活动中使用它: / p>
Here is how I use it in an Activity:
CategoriesDAO.getInstance().addOrUpdate(categories);
推荐答案
您可以将POJO daos的实例存储在在BaseDao本身或子类中映射,然后使用未经检查的转换来提取它。
You could store the instances of your POJO daos in a map either inside your BaseDao itself or in a subclass and then use an unchecked cast to extract it out.
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(....);
这篇关于使用SQLite处理POJO的DAO创建更好的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!