ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

android – 为单次运行应用程序只创建一次greenDAO数据库连接的最佳方法是什么?

2019-07-17 17:32:42  阅读:199  来源: 互联网

标签:android greendao


目前我正在一个类中创建greenDAO数据库连接(它在每个静态方法中打开连接)并在我需要的地方使用它.但我不确定这是否是最佳方式.
谁能建议一个更好的方法呢?

我的代码:

import com.knowlarity.sr.db.dao.DaoMaster;
import com.knowlarity.sr.db.dao.DaoMaster.DevOpenHelper;
import com.knowlarity.sr.db.dao.DaoSession;
import com.knowlarity.sr.db.dao.IEntity;

public class DbUtils {

    private static Object lockCallRecord =new Object();
    private DbUtils(){};

    public static boolean saveEntity(Context context , IEntity entity){
            boolean t=false;
            DevOpenHelper helper=null;
            SQLiteDatabase db=null;
            DaoMaster daoMaster=null;
            DaoSession daoSession =null;
            try{
               helper = new DaoMaster.DevOpenHelper(context, IConstant.DB_STRING, null);
               db = helper.getReadableDatabase();
               daoMaster = new DaoMaster(db);
               daoSession = daoMaster.newSession();
               //Some business logic here for fetching and inserting the data.
            }catch (Exception e){
               Log.e("saveEntity", e.getStackTrace().toString());
            }finally{
               if(daoSession!=null)daoSession.clear();
               daoMaster=null;
               if(db.isOpen())db.close();
               helper.close();
            }
            return t;
    }

解决方法:

您的方法导致数据库经常被加载,这是不必要的,可能会显着减慢您的应用程序.

打开数据库一次并将其存储在某处,并在需要时从那里请求它.

我个人使用全球DaoSession和本地DaoSessions.本地DaoSessions被用于会话缓存中不应该保留任何内容(即将新对象持久存储到数据库中,这可能只是非常罕见地使用或者执行一些查询会加载很多不太可能再次被重用的实体).

请记住,如果您在全局会话中使用该实体,那么更新本地DaoSession中的实体也是一个坏主意.如果这样做,全局会话中的缓存实体将不会更新,除非您清除全局会话的缓存,否则您将得到错误的结果!

因此,最安全的方法是始终只使用一个DaoSession或新的DaoSessions并且不使用全局和本地会话!

自定义应用程序类是个好地方,但任何其他类也都可以.

我是这样做的:

class DBHelper:

private SQLiteDatabase _db = null;
private DaoSession _session = null;

private DaoMaster getMaster() {
    if (_db == null) {
        _db = getDatabase(DB_NAME, false);
    }
    return new DaoMaster(_db);
}

public DaoSession getSession(boolean newSession) {
    if (newSession) {
        return getMaster().newSession();
    }
    if (_session == null) {
        _session = getMaster().newSession();
    }
    return _session;
}

private synchronized SQLiteDatabase getDatabase(String name, boolean readOnly) {
    String s = "getDB(" + name + ",readonly=" + (readOnly ? "true" : "false") + ")";
    try {
        readOnly = false;
        Log.i(TAG, s);
        SQLiteOpenHelper helper = new MyOpenHelper(context, name, null);
        if (readOnly) {
            return helper.getReadableDatabase();
        } else {
            return helper.getWritableDatabase();
        }
    } catch (Exception ex) {
        Log.e(TAG, s, ex);
        return null;
    } catch (Error err) {
        Log.e(TAG, s, err);
        return null;
    }
}

private class MyOpenHelper extends DaoMaster.OpenHelper {
    public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
        super(context, name, factory);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i(TAG, "Create DB-Schema (version "+Integer.toString(DaoMaster.SCHEMA_VERSION)+")");
        super.onCreate(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i(TAG, "Update DB-Schema to version: "+Integer.toString(oldVersion)+"->"+Integer.toString(newVersion));
        switch (oldVersion) {
            case 1:
                db.execSQL(SQL_UPGRADE_1To2);
            case 2:
                db.execSQL(SQL_UPGRADE_2To3);
                break;
            default:
                break;
        }
    }
}

在应用程序类中:

private static MyApplication _INSTANCE = null;

public static MyApplication getInstance() {
    return _INSTANCE;
}

@Override
public void onCreate() {
    _INSTANCE = this;
    // ...
}

private DBHelper _dbHelper = new DBHelper();

public static DaoSession getNewSession() {
    return getInstance()._dbHelper.getSession(true);
}

public static DaoSession getSession() {
    return getInstance()._dbHelper.getSession(false);
}

当然,您也可以存储DaoMaster而不是DB本身.这将减少一些小的开销.

我每次使用一些常用方法(比如访问数据库)时都使用类似Singleton的Application类和静态方法来避免转换应用程序(((MyApplication)getApplication())).

标签:android,greendao
来源: https://codeday.me/bug/20190717/1490883.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有