什么是创造greenDAO DB连接只有一次申请单次运行的最好方法是什么? [英] What is the best way of creating greenDAO DB connection only once for single run of application?

查看:182
本文介绍了什么是创造greenDAO DB连接只有一次申请单次运行的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我创造了一类greenDAO数据库连接(这将打开每一个静态方法的连接),并使用它,无论我需要它。但我不知道这是否是做的最好的方式。 任何人都可以提出这样做​​的更好的办法?

我的code:

 进口com.knowlarity.sr.db.dao.DaoMaster;
进口com.knowlarity.sr.db.dao.DaoMaster.DevOpenHelper;
进口com.knowlarity.sr.db.dao.DaoSession;
进口com.knowlarity.sr.db.dao.IEntity;

公共类DbUtils {

    私有静态对象lockCallRecord =新的对象();
    私人DbUtils(){};

    公共静态布尔saveEntity(上下文的背景下,IEntity实体){
            布尔T = FALSE;
            DevOpenHelper帮手= NULL;
            SQLiteDatabase DB = NULL;
            DaoMaster daoMaster = NULL;
            DaoSession daoSession = NULL;
            尝试{
               辅助=新DaoMaster.DevOpenHelper(背景下,IConstant.DB_STRING,NULL);
               DB = helper.getReadableDatabase();
               daoMaster =新DaoMaster(DB);
               daoSession = daoMaster.newSession();
               //一些业务逻辑这里获取和插入的数据。
            }赶上(例外五){
               Log.e(saveEntity,e.getStackTrace()的toString());
            }最后{
               如果(!daoSession = NULL)daoSession.clear();
               daoMaster = NULL;
               如果(db.isOpen())db.close();
               helper.close();
            }
            返回吨;
    }
 

解决方案

您的做法会导致数据库被加载很多时候这是没有必要的,可能你的应用程序显著放缓。

打开数据库一次,并存储在某个地方,并从在需要时有提出要求。

我个人使用一个全球性的 DaoSession 和地方 DaoSession 秒。当地 DaoSession 取值习惯在这里没有什么应该保持会话缓存(即坚持一个新的对象到数据库中,这很可能是只用非常罕见的或执行一些查询这会加载很多是不太可能被再次重用实体)的。

请记住,在本地 DaoSession 更新的实体是一个坏主意,如果你使用的实体在全局会议上也是如此。如果你这样做了缓存的实体在全局会议将不会被更新,除非你明确的全球会议的缓存,你会得到错误的结果!

因此,最安全的办法是要么只使用一个 DaoSession 或新的 DaoSession 一切都是时间并且不使用全局和局部的会议!

一个自定义的应用程序类是个好地方,但任何其他类也都会好的。

这是我如何做到这一点:

类DBHelper:

 私人SQLiteDatabase _db = NULL;
私人DaoSession _session = NULL;

私人DaoMaster getMaster(){
    如果(_db == NULL){
        _db = getDatabase(DB_NAME,假);
    }
    返回新DaoMaster(_db);
}

公共DaoSession的getSession(布尔newsession的){
    如果(newsession的){
        返回getMaster()newsession的()。
    }
    如果(_session == NULL){
        _session = getMaster()newsession的()。
    }
    返回_session;
}

私人同步SQLiteDatabase getDatabase(字符串名称,布尔只读){
    字符串s =getDB(+名称+,只读=+(readOnly的真:假)+);
    尝试 {
        readOnly的= FALSE;
        Log.i(TAG,S);
        SQLiteOpenHelper帮助=新MyOpenHelper(背景下,名,NULL);
        如果(只读){
            返回helper.getReadableDatabase();
        } 其他 {
            返回helper.getWritableDatabase();
        }
    }赶上(例外前){
        Log.e(TAG,S,EX);
        返回null;
    }赶上(误差err){
        Log.e(TAG,S,ERR);
        返回null;
    }
}

私有类MyOpenHelper扩展DaoMaster.OpenHelper {
    公共MyOpenHelper(上下文的背景下,字符串名称,SQLiteDatabase.CursorFactory厂){
        超(背景下,名称,出厂);
    }

    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        Log.i(TAG,创建DB-模式(版本+ Integer.toString(DaoMaster.SCHEMA_VERSION)+));
        super.onCreate(DB);
    }

    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        Log.i(TAG,更新DB-模式到版本:+ Integer.toString(oldVersion)+ - >中+ Integer.toString(动态网页));
        开关(oldVersion){
            情况1:
                db.execSQL(SQL_UPGRADE_1To2);
            案例2:
                db.execSQL(SQL_UPGRADE_2To3);
                打破;
            默认:
                打破;
        }
    }
}
 

在应用程序类:

 私有静态MyApplication的_instance = NULL;

公共静态所有MyApplication的getInstance(){
    返回_instance;
}

@覆盖
公共无效的onCreate(){
    _instance =这一点;
    // ...
}

私人DBHelper _dbHelper =新DBHelper();

公共静态DaoSession getNewSession(){
    返回的getInstance()._ dbHelper.getSession(真正的);
}

公共静态DaoSession的getSession(){
    返回的getInstance()._ dbHelper.getSession(假);
}
 

当然,你也可以存储DaoMaster,而不是数据库本身。这将减少一些小的开销。

我使用一个Singleton类应用类和静态方法是避免在应用程序(((MyApplication的)getApplication()))每次我用一些时间的常用方法(如在访问DB)

Currently I am creating the greenDAO DB connection in a class (which opens the connection in every static method) and using it wherever I need it. But I am not sure if it's the best way of doing it. Can anyone suggest a better way of doing it?

My Code:

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;
    }

解决方案

Your approach causes the database to be loaded very often which is not necessary and may slow down your app significantly.

Open the database once and store it somewhere and request it from there if needed.

Personally I use a global DaoSession and local DaoSessions. The local DaoSessions get used where nothing should remain in the session cache (i.e. persisting a new object into the database, that is likely to be used only very infrequent or performing some queries which will load a lot of entities that are unlikely to be reused again).

Keep in mind that updating entities in a local DaoSession is a bad idea if you use the entity in your global session as well. If you do this the cached entity in your global session won't be updated and you will get wrong results unless you clear the cache of the global session!

Thus the safest way is to either just use one DaoSession or new DaoSessions all the time and to not use a global and local sessions!!!

A custom application class is a good place, but any other class will also be ok.

This is how I do it:

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;
        }
    }
}

In application class:

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);
}

Of course you can also store the DaoMaster instead of the DB itself. This will reduce some small overhead.

I'm using a Singleton-like Application class and static methods to avoid casting the application (((MyApplication)getApplication())) every time I use some of the common methods (like accessing the DB).

这篇关于什么是创造greenDAO DB连接只有一次申请单次运行的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆