4

我开始开发android应用程序几个月了。我已经使用 Spring 框架和 Hibernate 工作了大约两年。因此,在搜索适用于 android 的 ORM 工具时,我找到了 ormlite 项目。我发现它非常有趣,我决定在我的应用程序中使用它。

一切似乎都很好,但我会向专家询问一些关于使用 ormlite 以高效和(如果可能的话)优雅的方式开发 android 应用程序的技巧!

让我们从域类开始。

所有域类都实现了一个伪 DomainObject 接口:

@DatabaseTable(tableName = "job")
public final class  Job implements DomainObject{

    @DatabaseField(generatedId = true, columnName="_id")
    public Integer id;

    @DatabaseField(index=true)
    public Integer remoteDbid;

    @DatabaseField
    public Date downloadDate;

    @DatabaseField
    public Date assignedDate;
     .....
}

然后我有一个通用的 Dao 接口

public interface GenericDao <T extends DomainObject> {
    T queryForId(Integer id);
    List<T> queryForAll();
    void save(T object);
    void merge(T object);   
    void delete(T object);
}

实施者:

public class GenericDaoORM <T extends DomainObject> extends OrmLiteSqliteOpenHelper implements GenericDao<T>{

    private static final String LOG_TAG = GenericDaoORM.class.getSimpleName();

    private final static int DATABASE_VERSION = 7;

    private final Class<T> type;
    protected Dao<T, Integer> dao = null;

    protected GenericDaoORM(final Context context, final Class<T> type) {
        super(context, FileConfig.DB_PATH, null, DATABASE_VERSION);
        this.type = type;
        if (dao == null) {
            try {
                dao = getDao(type);
            } catch (SQLException e) {
                if (LogConfig.ENABLE_ACRA){
                    ErrorReporter.getInstance().handleException(e);
                }
                if (LogConfig.ERROR_LOGS_ENABLED){
                    Log.e(LOG_TAG, "Can't get DAO for "+type.getName(), e);
                }
            }
                }
    }

    @Override
    public T queryForId(final Integer id) {
        try {
            return dao.queryForId(id);
        } catch (SQLException e) {
            if (LogConfig.ENABLE_ACRA){
                ErrorReporter.getInstance().handleException(e);
            }
            if (LogConfig.ERROR_LOGS_ENABLED){
                Log.e(LOG_TAG, "Can't get element with id "+id, e);
            }
            return null;
        }
    }

    @Override
    public List<T> queryForAll() {
        try {
            return dao.queryForAll();
        } catch (SQLException e) {
            if (LogConfig.ENABLE_ACRA){
                ErrorReporter.getInstance().handleException(e);
            }
            if (LogConfig.ERROR_LOGS_ENABLED){
                Log.e(LOG_TAG, "Can't get "+ type.getName() +" list", e);
            }
            return null;
        }
    }

    @Override
    public void save(final T object) {
        try {
            dao.create(object);
        } catch (SQLException e) {
            if (LogConfig.ENABLE_ACRA){
                ErrorReporter.getInstance().handleException(e);
            }
            if (LogConfig.ERROR_LOGS_ENABLED){
                Log.e(LOG_TAG, "Can't save "+ object.getClass().getName(), e);
            }
        }
    }

    @Override
    public void merge(final T object) {
        try {
            dao.update(object);
        } catch (SQLException e) {
            if (LogConfig.ENABLE_ACRA){
                ErrorReporter.getInstance().handleException(e);
            }
            if (LogConfig.ERROR_LOGS_ENABLED){
                Log.e(LOG_TAG, "Can't update "+ object.getClass().getName(), e);
            }
        }
    }

    @Override
    public void delete(final T object) {
        try {
            dao.delete(object);
        } catch (SQLException e) {
            if (LogConfig.ENABLE_ACRA){
                ErrorReporter.getInstance().handleException(e);
            }
            if (LogConfig.ERROR_LOGS_ENABLED){
                Log.e(LOG_TAG, "Can't delete "+ object.getClass().getName(), e);
            }
        }
    }

    @Override
    public void onCreate(final SQLiteDatabase database, final ConnectionSource connectionSource) {
        try {
            TableUtils.createTableIfNotExists(connectionSource, Job.class);                 
        } catch (SQLException e) {
            if (LogConfig.ENABLE_ACRA){
                ErrorReporter.getInstance().handleException(e);
            }
            if (LogConfig.ERROR_LOGS_ENABLED){
                Log.e(LOG_TAG, "Cannot create Tables", e);
            }
        }
    }

    @Override
    public void onUpgrade(final SQLiteDatabase database, final ConnectionSource connectionSource, final int oldVersion, final int newVersion) {
        onCreate(database, connectionSource);       
    }
}

每个域对象都有自己的 Dao 接口,定义了额外的方法(以防万一需要其他方法而不是 GenericDao 中定义的方法):

public interface JobDao extends GenericDao<Job>{
    Cursor getReceivedJobs();
        ... 
}

和相关的实现:

public final class JobDaoORM extends GenericDaoORM<Job> implements JobDao {
    private static final String LOG_TAG = JobDaoORM.class.getSimpleName();

    public JobDaoORM(final Context context) {
            super(context, Job.class);
        }

    public Cursor getReceivedJobs() {
        try{
            final QueryBuilder<Job, Integer> queryBuilder = dao.queryBuilder();
            queryBuilder.orderBy("reportDate", false);
            queryBuilder.selectColumns(new String[]{"...", "...", ...});
            final Where<Job, Integer> where = queryBuilder.where();
            where.eq("executed", true);
            final PreparedQuery<Job> preparedQuery = queryBuilder.prepare();
            final AndroidCompiledStatement compiledStatement =
                    (AndroidCompiledStatement)preparedQuery.compile(connectionSource.getReadOnlyConnection(),StatementType.SELECT);
            return compiledStatement.getCursor();
        } catch (SQLException e) {
            if (LogConfig.ENABLE_ACRA){
                ErrorReporter.getInstance().handleException(e);
            }
            if (LogConfig.ERROR_LOGS_ENABLED){
                Log.e(LOG_TAG, "getReceivedJobs()", e);
            }
        }
        return null;
    }
}

所以我的问题是...

1)这种领域/道的实现是高性能的还是我引入了冗余且不必要的代码?

2)这是使用 ormlite 的好方法吗?

3)将每个 dao 的实例保存在扩展 Application 的类中是一种好习惯,还是在每个活动上保留一个 dao 的实例或保存在其他地方更好?

我也尝试过处理事务,但没有成功。我得到一个异常说表被锁定。我在 GenericDao 中创建了一个方法,返回一个新的 TransactionManager 实例:

public interface GenericDao <T extends DomainObject> {
    ....
    TransactionManager getTransactionManager();
}

public class GenericDaoORM <T extends DomainObject> extends OrmLiteSqliteOpenHelper implements GenericDao<T>{
...
    @Override
    public TransactionManager getTransactionManager(){
        return new TransactionManager(getConnectionSource());
    }
}

但是当我在事务更新数据库中执行代码时,我遇到了一个异常......

谢谢您的答复!

马可

4

0 回答 0