【问题标题】:ActiveRecord with ORMLite使用 ORMLite 的 ActiveRecord
【发布时间】:2012-04-28 01:06:06
【问题描述】:

我真的很喜欢主动记录的想法,我将实现以下设计: 所有具体模型都扩展了抽象模型,抽象模型具有基本的 CRUD 操作。

这是模型上的示例保存功能:

public void save(){
    try {
        getDao().createOrUpdate(this);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

这里是getDao():

private static Dao<Model, Integer> getDao(Context context){
    Dao<Model, Integer> result = null;

    DatabaseHelper dbHelper = new DatabaseHelper(context);
    try {
        result = dbHelper.getDao(Model.class);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       

    return result;
}

如您所见,我有 Model.class。除了将 Class 传递给 getDao 函数之外,是否还有其他选项或模式可以实现以下设计?

【问题讨论】:

    标签: android database dao


    【解决方案1】:

    不要将getDao 方法设为静态,然后:

    result = dbHelper.getDao(getClass());
    

    编辑:

    在这种情况下,您必须以某种方式告诉 getDao 方法要获取什么 dao。你可以使用类似的东西:

    private static <T> Dao getDao(Context context, T object){
        try {
            return new DatabaseHelper(context).getDao(object.getClass());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    

    【讨论】:

    • 如果它不是静态的,那么我不能将它用于 getAll 函数(静态)。
    • 好的,然后让我做一些其他的改变:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    相关资源
    最近更新 更多