GreenDao3.0使用

来源:互联网 发布:好的莆田鞋淘宝店 编辑:程序博客网 时间:2024/06/03 12:13

第一步,导入greenDao3.0包以及数据库升级库:
app build.gradle

compile 'org.greenrobot:greendao:3.2.2'//greenDaocompile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v1.3.0'//greenDao升级

在android{}里加入

 sourceSets {        main {            manifest.srcFile 'src/main/AndroidManifest.xml'            java.srcDirs = ['src/main/java', 'src/main/java-gen']            res.srcDirs = ['src/main/res']        }    } greendao {        daoPackage 'greendao'        schemaVersion 1//数据库版本号        targetGenDir 'src/main/java-gen'//设置DaoMaster、DaoSession、Dao目录        //targetGenDirTest:设置生成单元测试目录        //generateTests:设置自动生成单元测试用例    }

在最上面添加:

apply plugin: 'org.greenrobot.greendao' // apply plugin  greenDao

根目录 build.gradle

buildscript {    repositories {        jcenter()        maven { url "https://jitpack.io" }//升级数据库工具类添加        mavenCentral() // add repository   greenDao    }    dependencies {        classpath 'com.android.tools.build:gradle:2.3.1'        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        jcenter()        maven { url "https://jitpack.io" }//升级数据库工具类添加    }}task clean(type: Delete) {    delete rootProject.buildDir}

第二步,在与java包同级目录下创建java-gen/greendao(切记只能小写,不能有任何大写字母)目录;
第三步,创建一个bean.java,例如:
UserBean.java:

@Entitypublic class UserBean {    @Id(autoincrement = true)    private Long id;    @NotNull    private String name;    @NotNull    private String photo;    private String feature;    private Long createTime;//创建时间    private Long updateTime;//更新时间}

点击Build –> Make Project就会自动生成各项需要的文件了,接下来就是配置一些工具类,参考下面的文件

第四步,在utils工具包下添加greenDao文件夹,添加文件MySQLiteOpenHelper.java和
GreenDaoHelper.java;
文件GreenDaoHelper.java:

package com.raf.facesdkdemo.untils.greendao;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import com.github.yuweiguocn.library.greendao.MigrationHelper;import com.raf.facesdkdemo.bean.UserBean;import com.raf.facesdkdemo.untils.LogUtil;import org.greenrobot.greendao.database.Database;import greendao.DaoMaster;import greendao.DaoSession;import greendao.UserBeanDao;public class GreenDaoHelper {    private static DaoMaster.DevOpenHelper devOpenHelper;    private static MySQLiteOpenHelper helper;    private static SQLiteDatabase database;//不知道跟下面啥区别    private static Database db;//不知道跟上面啥区别    private static DaoMaster daoMaster;    private static DaoSession daoSession;    //倒叙查找 .orderDesc()    /**     * 初始化greenDao     * 加入升级库的初始化方法     */    public static void initDatabase(Context context) {        // 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。        // 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。        // 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。//        devOpenHelper = new DaoMaster.DevOpenHelper(context, "visitorSystem_db", null);//数据库名        MigrationHelper.DEBUG = true; //如果你想查看日志信息,请将DEBUG设置为true        helper = new MySQLiteOpenHelper(context, "faceSDK_db",                null);        //加密//        helper.getEncryptedWritableDb("<your-secret-password>");        database = helper.getWritableDatabase();        // 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。        daoMaster = new DaoMaster(database);        daoSession = daoMaster.newSession();        //设置数据//        setSetting(context);    }    /**     * greenDao官方 初始化方法     */    public static void initDatabase2(Context context) {        // Application 中执行        // DevOpenHelper 每次数据库升级会清空数据,一般用于开发        devOpenHelper = new DaoMaster.DevOpenHelper(context, "visitorSystem_db", null);        db = devOpenHelper.getWritableDb();        daoSession = new DaoMaster(db).newSession();//// 在使用的地方获取 DAO//        NoteDao noteDao = daoSession.getNoteDao();//        setSetting(context);    }    public static DaoSession getDaoSession() {        return daoSession;    }    public static SQLiteDatabase getDb() {        return database;    }    public static UserBeanDao getUserBeanDao() {        return getDaoSession().getUserBeanDao();    }    /**     * --------------------------------获取数据操作工具类-------------------------------------------     */    /**     * -----------------插入数据--------------------------------------------------------------     */    public static void insertData(UserBean bean) {        getUserBeanDao().insert(bean);//id传null 即自增。==> 这里是Long类型而不是long    }    /**     * ------------------删除数据----------------------------------------------------------------     */    public static boolean deleteById(UserBean bean) {        //查询id等于positonId        UserBean userBean = getUserBeanDao().                queryBuilder().where(UserBeanDao.Properties.Id.eq(bean.getId())).build().unique();        if (userBean == null) {            LogUtil.e("用户不存在!");            return false;        } else {            getUserBeanDao().deleteByKey(userBean.getId());            LogUtil.i("删除成功!");            return true;        }    }    /**     * -----------------修改----------------------------------------------------------------------     */    public static boolean updateById(UserBean newBean) {        UserBean bean2 = getUserBeanDao().                queryBuilder().where(UserBeanDao.Properties.Id.                eq(newBean.getId())).build().unique();        if (bean2 == null) {            LogUtil.e("id不存在");            return false;        } else {            getUserBeanDao().update(newBean);            LogUtil.i("修改成功!");            return true;        }    }}

文件MySQLiteOpenHelper.java:

package com.raf.visitorstothesystem.utils.greendao;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import com.github.yuweiguocn.library.greendao.MigrationHelper;import greendao.AdminBeanDao;import greendao.DaoMaster;import greendao.DepartmentBeanDao;import greendao.IntervieweeBeanDao;import greendao.SettingActionBeanDao;import greendao.VisitingReasonBeanDao;import greendao.VisitorInfoBeanDao;/** * greenDao数据库升级类 * Created by Kevin on 2017/4/25. */public class MySQLiteOpenHelper  extends DaoMaster.OpenHelper {    public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {        super(context, name, factory);    }    /**     * 更新数据库     * @param db     * @param oldVersion     * @param newVersion     */    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//        super.onUpgrade(db,oldVersion,newVersion);        //todo 加入所有有的xxxBeanDao.class        MigrationHelper.migrate(db,                AdminBeanDao.class,                DepartmentBeanDao.class,                IntervieweeBeanDao.class,                SettingActionBeanDao.class,                VisitingReasonBeanDao.class,                VisitorInfoBeanDao.class        );    }}

第五步,在MyApplication.java里加入初始化:

//初始化数据库GreenDaoHelper.initDatabase(this);

ps:我是在一步一步的跟着做,因为以前做过了后面步骤居然忘记了,所以这里做个笔记,方便后来参考。