GreenDao 3.2.2 使用总结

1  module  gradle配置

    

apply plugin: 'org.greenrobot.greendao'
greendao {
    schemaVersion 5    //每次数据库升级+1
    daoPackage 'xx.xx.xx.greendao.gen'
    targetGenDir 'src/main/java'
}
dependencies {

    compile 'org.greenrobot:greendao:3.2.2'
    compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v2.0.0'//数据库升级工具
}

2. 创建GreenDao工具类 GreenDaoManager 

public class GreenDaoManager {
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private static GreenDaoManager mInstance; //单例
    private GreenDaoOpenHelper openHelper;

    private GreenDaoManager() {
        SLFLogUtils.e("当前数据库版本号:"+SCHEMA_VERSION);
        if (mInstance == null) {
            openHelper = new
                    GreenDaoOpenHelper(PosApplication.mContext, "/sdcard/xxx/xx-db", null);
            mDaoMaster = new DaoMaster(openHelper.getWritableDatabase());

            mDaoSession = mDaoMaster.newSession();
        }
    }

    public static GreenDaoManager getInstance() {
        if (mInstance == null) {
            synchronized (GreenDaoManager.class) {//保证异步处理安全操作
                if (mInstance == null) {
                    mInstance = new GreenDaoManager();
                }
            }
        }
        return mInstance;
    }

    public DaoSession getSession() {
        return mDaoSession;
    }

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

        @Override
        public void onUpgrade(Database db, int oldVersion, int newVersion) {
            SLFLogUtils.e(oldVersion + "升级到----->" + newVersion);
            MigrationHelper.DEBUG = true;
            MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {

                @Override
                public void onCreateAllTables(Database db, boolean ifNotExists) {
                    DaoMaster.createAllTables(db, ifNotExists);
                }

                @Override
                public void onDropAllTables(Database db, boolean ifExists) {
                    DaoMaster.dropAllTables(db, ifExists);
                }
            }, SerialBeanDao.class, ReverseBeanDao.class, UserBeanDao.class);
        }
    }

}
3.Application 初始化类GreenDaoManager 

public static GreenDaoManager dbManager;
dbManager = GreenDaoManager.getInstance();

4.创建Bean

@Entity
public class xxxBean {
    @Id(autoincrement = true)
    private Long id;
    //xxx
    private Byte xxx;
    //xxx
    private String xxxx;

    }
编译后studio自动创建set get  以备读取数据库字段值

5. 使用

SerialBeanDao serialBeanDao = PosApplication.dbManager.getSession().getxxxBeanDao();
具体方法请参照GreenDao sdk使用说明,详见如下地址
http://greenrobot.org/greendao/documentation/queries/




你可能感兴趣的:(android)