GreenDao使用详解、封装、优化升级

GreenDao

http://greenrobot.org/greendao/documentation/ 官网介绍地址

Android开发数据库的第三方框架,据说效率高,不过比原生升级方便多了。写给自己以后方便查看,共享给大家一起学习使用。

1、工程build.gradle下

buildscript {

    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
        google()
        mavenCentral()//***GreenDao需要增加
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'//***GreenDao需要增加
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

2、moudle里的build.gradle

android {
	..............
    // In your app projects build.gradle file:
    apply plugin: 'com.android.application'
    apply plugin: 'org.greenrobot.greendao'
    greendao {
        schemaVersion 1  //版本号
        daoPackage 'com.study.test.testapplication.db'  //包名+dbName
        targetGenDir 'src/main/java'  //db路径
    }
}
dependencies {
         ......
	implementation 'org.greenrobot:greendao:3.2.2'
}

3、项目同步下,重新BUILD一遍

4、MyApplication 初始化

public class MyApplication extends Application {

    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;

    public static MyApplication instances;

    @Override
    public void onCreate() {
        super.onCreate();
        instances = this;
        setDatabase();
    }

    /**
     * 单例模式
     *
     * @return
     */
    public static MyApplication getInstances() {
        return instances;
    }
    /**
     * 设置greenDao
     */
    private void setDatabase() {
        // 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO 已经帮你做了。
        // 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
        // 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
        mHelper = new DaoMaster.DevOpenHelper(this, "test-db", null);
        db = mHelper.getWritableDatabase();
        // 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    public  DaoSession getDaoSession() {
        return mDaoSession;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

}

5、创建一个User表实体类:

@Entity
public class User {
    @Id(autoincrement = true)
    private Long id;

    @NotNull
    private String name;
    private String sex;
    private String age;
    private String email;

    .....中间的代码build会自己生成...
}

6、创建SQLUtils

public class SQLiteUtils {
    private static SQLiteUtils instance;
    private UserDao userEntityDao;
    private DaoSession daoSession;
    private DaoMaster.DevOpenHelper helper;

    private SQLiteUtils() {
        daoSession = MyApplication.getInstances().getDaoSession();
        userEntityDao = daoSession.getUserDao();
        QueryBuilder.LOG_VALUES=true;
        QueryBuilder.LOG_SQL=true;
    }

    public static SQLiteUtils getInstance() {
        if (instance == null) {
            synchronized (SQLiteUtils.class) {
                if (instance == null) {
                    instance = new SQLiteUtils();
                }
            }
        }
        return instance;
    }

    //增加
    public void addUser(User testBean) {
        userEntityDao.insert(testBean);
    }

    //删除
    public void deleteUser(User testBean) {
        userEntityDao.delete(testBean);
    }

    //修改
    public void updateUser(User testBean) {
        userEntityDao.update(testBean);
    }

 /**
     * 根据年龄,修改数据
     * @param age
     * @param user
     */
    public void updateWhereAgeUser(String age,User user){
        daoSession.getDatabase().execSQL("update user set age=? where age=?and email=?",new Object[]{age,user.getAge(),user.getEmail()});
    }

    //查询所有
    public List<User> selectAllUser() {
        userEntityDao.detachAll();//清除缓存
        List<User> list1 = userEntityDao.loadAll();
        return list1 == null ? new ArrayList<User>() : list1;
    }

    //条件查询
    public List<User> selectWhereAge(String age) {
        QueryBuilder<User> queryBuilder = userEntityDao.queryBuilder().where(UserDao.Properties.Age.eq(age));
        return queryBuilder.list();
    }

    //删除表中内容
    public void deleteAllUser() {
        userEntityDao.deleteAll();
    }

   /**
     * 条件删除表中数据
     * @param age [条件]
     */
    public void deletewhereAge(String age) {
        daoSession.getDatabase().execSQL("delete from user where age=?",new Object[]{age});
    }

    /**
     * 关闭所有的操作
     * 注:数据库开启之后,使用完毕必须要关闭
     */
    public void closeConnection() {
        closeHelper();
        closeDaoSession();
    }

    private void closeHelper() {
        if (helper != null) {
            helper.close();
            helper = null;
        }
    }

    private void closeDaoSession() {
        if (daoSession != null) {
            daoSession.clear();
            daoSession = null;
        }
    }
}

7、使用SQLUtils操作GreenDao

  1. 插入数据
SQLiteUtils.getInstance().addUser(new User(null, "name", "sex", "10", "email"));
  1. 查询数据
//所有数据查询
SQLiteUtils.getInstance().selectAllUser();

//条件查询
SQLiteUtils.getInstance().selectWhereAge(10);

  1. 修改数据

SQLiteUtils.getInstance().updateWhereAgeUser("10",new User(null, "name1221", "sex", "22", "email"));

  1. 删除数据
//这种默认,通过id条件
SQLiteUtils.getInstance().deletewhereAge(new User());

//条件修改
SQLiteUtils.getInstance().deletewhereAge("1000");

GreenDao封装 解决 升级数据库丢失原数据

1、使用的是Github上的框架
【1】添加依赖,根据GreenDao的版本选择依赖版本

1、封装MyOpenHelper

public class MyOpenHelper extends DaoMaster.DevOpenHelper {

    public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
        super(context, name, factory);
    }

    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
//        super.onUpgrade(db, oldVersion, newVersion);  //记得注释哦!!!

        if (oldVersion < newVersion) {
            Log.i("version", oldVersion + "---先前和更新之后的版本---" + newVersion);
        }

        MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
            @Override
            public void onCreateAllTables(Database db, boolean ifNotExists) {
                Log.e("chenxh","ifNotExists:"+ifNotExists);
                DaoMaster.createAllTables(db, ifNotExists);
            }
            @Override
            public void onDropAllTables(Database db, boolean ifExists) {
                Log.e("chenxh","ifExists:"+ifExists);
                DaoMaster.dropAllTables(db, true);
            }
        },UserDao.class);//需要添加表,加全,不要漏
    }
}

3、在Myapplication中创建数据库:

public class MyApplication extends Application {

    private MyOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;

    public static MyApplication instances;

    @Override
    public void onCreate() {
        super.onCreate();
        instances = this;
        setDatabase();
    }

    /**
     * 单例模式
     *
     * @return
     */
    public static MyApplication getInstances() {
        return instances;
    }

    /**
     * 设置greenDao
     */
    private void setDatabase() {
        //第三方升级库
        MigrationHelper.DEBUG = true;
        //封装的Daomaster 主要封装了升级保存数据的方法
        mHelper = new MyOpenHelper(this, "test-db", null);
        db = mHelper.getWritableDatabase();
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();

    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

}

有疑问可以发邮件[email protected]

你可能感兴趣的:(Android,在旅行)